e3c11ccb561f86197a4b2c71eedc61f9a557f035
[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|bool
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 # Get the token from DB/cache and clean it up to remove garbage padding.
987 # This deals with historical problems with bugs and the default column value.
988 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
989 $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) );
990 $from = 'cookie';
991 } else {
992 # No session or persistent login cookie
993 return false;
994 }
995
996 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
997 $this->loadFromUserObject( $proposedUser );
998 $request->setSessionData( 'wsToken', $this->mToken );
999 wfDebug( "User: logged in from $from\n" );
1000 return true;
1001 } else {
1002 # Invalid credentials
1003 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1004 return false;
1005 }
1006 }
1007
1008 /**
1009 * Load user and user_group data from the database.
1010 * $this->mId must be set, this is how the user is identified.
1011 *
1012 * @return Bool True if the user exists, false if the user is anonymous
1013 */
1014 public function loadFromDatabase() {
1015 # Paranoia
1016 $this->mId = intval( $this->mId );
1017
1018 /** Anonymous user */
1019 if( !$this->mId ) {
1020 $this->loadDefaults();
1021 return false;
1022 }
1023
1024 $dbr = wfGetDB( DB_MASTER );
1025 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1026
1027 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1028
1029 if ( $s !== false ) {
1030 # Initialise user table data
1031 $this->loadFromRow( $s );
1032 $this->mGroups = null; // deferred
1033 $this->getEditCount(); // revalidation for nulls
1034 return true;
1035 } else {
1036 # Invalid user_id
1037 $this->mId = 0;
1038 $this->loadDefaults();
1039 return false;
1040 }
1041 }
1042
1043 /**
1044 * Initialize this object from a row from the user table.
1045 *
1046 * @param $row Array Row from the user table to load.
1047 * @param $data Array Further user data to load into the object
1048 *
1049 * user_groups Array with groups out of the user_groups table
1050 * user_properties Array with properties out of the user_properties table
1051 */
1052 public function loadFromRow( $row, $data = null ) {
1053 $all = true;
1054
1055 $this->mGroups = null; // deferred
1056
1057 if ( isset( $row->user_name ) ) {
1058 $this->mName = $row->user_name;
1059 $this->mFrom = 'name';
1060 $this->setItemLoaded( 'name' );
1061 } else {
1062 $all = false;
1063 }
1064
1065 if ( isset( $row->user_real_name ) ) {
1066 $this->mRealName = $row->user_real_name;
1067 $this->setItemLoaded( 'realname' );
1068 } else {
1069 $all = false;
1070 }
1071
1072 if ( isset( $row->user_id ) ) {
1073 $this->mId = intval( $row->user_id );
1074 $this->mFrom = 'id';
1075 $this->setItemLoaded( 'id' );
1076 } else {
1077 $all = false;
1078 }
1079
1080 if ( isset( $row->user_editcount ) ) {
1081 $this->mEditCount = $row->user_editcount;
1082 } else {
1083 $all = false;
1084 }
1085
1086 if ( isset( $row->user_password ) ) {
1087 $this->mPassword = $row->user_password;
1088 $this->mNewpassword = $row->user_newpassword;
1089 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1090 $this->mEmail = $row->user_email;
1091 if ( isset( $row->user_options ) ) {
1092 $this->decodeOptions( $row->user_options );
1093 }
1094 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1095 $this->mToken = $row->user_token;
1096 if ( $this->mToken == '' ) {
1097 $this->mToken = null;
1098 }
1099 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1100 $this->mEmailToken = $row->user_email_token;
1101 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1102 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1103 } else {
1104 $all = false;
1105 }
1106
1107 if ( $all ) {
1108 $this->mLoadedItems = true;
1109 }
1110
1111 if ( is_array( $data ) ) {
1112 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1113 $this->mGroups = $data['user_groups'];
1114 }
1115 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1116 $this->loadOptions( $data['user_properties'] );
1117 }
1118 }
1119 }
1120
1121 /**
1122 * Load the data for this user object from another user object.
1123 *
1124 * @param $user User
1125 */
1126 protected function loadFromUserObject( $user ) {
1127 $user->load();
1128 $user->loadGroups();
1129 $user->loadOptions();
1130 foreach ( self::$mCacheVars as $var ) {
1131 $this->$var = $user->$var;
1132 }
1133 }
1134
1135 /**
1136 * Load the groups from the database if they aren't already loaded.
1137 */
1138 private function loadGroups() {
1139 if ( is_null( $this->mGroups ) ) {
1140 $dbr = wfGetDB( DB_MASTER );
1141 $res = $dbr->select( 'user_groups',
1142 array( 'ug_group' ),
1143 array( 'ug_user' => $this->mId ),
1144 __METHOD__ );
1145 $this->mGroups = array();
1146 foreach ( $res as $row ) {
1147 $this->mGroups[] = $row->ug_group;
1148 }
1149 }
1150 }
1151
1152 /**
1153 * Add the user to the group if he/she meets given criteria.
1154 *
1155 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1156 * possible to remove manually via Special:UserRights. In such case it
1157 * will not be re-added automatically. The user will also not lose the
1158 * group if they no longer meet the criteria.
1159 *
1160 * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
1161 *
1162 * @return array Array of groups the user has been promoted to.
1163 *
1164 * @see $wgAutopromoteOnce
1165 */
1166 public function addAutopromoteOnceGroups( $event ) {
1167 global $wgAutopromoteOnceLogInRC;
1168
1169 $toPromote = array();
1170 if ( $this->getId() ) {
1171 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1172 if ( count( $toPromote ) ) {
1173 $oldGroups = $this->getGroups(); // previous groups
1174 foreach ( $toPromote as $group ) {
1175 $this->addGroup( $group );
1176 }
1177 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1178
1179 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1180 $logEntry->setPerformer( $this );
1181 $logEntry->setTarget( $this->getUserPage() );
1182 $logEntry->setParameters( array(
1183 '4::oldgroups' => $oldGroups,
1184 '5::newgroups' => $newGroups,
1185 ) );
1186 $logid = $logEntry->insert();
1187 if ( $wgAutopromoteOnceLogInRC ) {
1188 $logEntry->publish( $logid );
1189 }
1190 }
1191 }
1192 return $toPromote;
1193 }
1194
1195 /**
1196 * Clear various cached data stored in this object. The cache of the user table
1197 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1198 *
1199 * @param $reloadFrom bool|String Reload user and user_groups table data from a
1200 * given source. May be "name", "id", "defaults", "session", or false for
1201 * no reload.
1202 */
1203 public function clearInstanceCache( $reloadFrom = false ) {
1204 $this->mNewtalk = -1;
1205 $this->mDatePreference = null;
1206 $this->mBlockedby = -1; # Unset
1207 $this->mHash = false;
1208 $this->mRights = null;
1209 $this->mEffectiveGroups = null;
1210 $this->mImplicitGroups = null;
1211 $this->mGroups = null;
1212 $this->mOptions = null;
1213 $this->mOptionsLoaded = false;
1214 $this->mEditCount = null;
1215
1216 if ( $reloadFrom ) {
1217 $this->mLoadedItems = array();
1218 $this->mFrom = $reloadFrom;
1219 }
1220 }
1221
1222 /**
1223 * Combine the language default options with any site-specific options
1224 * and add the default language variants.
1225 *
1226 * @return Array of String options
1227 */
1228 public static function getDefaultOptions() {
1229 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1230
1231 static $defOpt = null;
1232 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1233 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1234 // mid-request and see that change reflected in the return value of this function.
1235 // Which is insane and would never happen during normal MW operation
1236 return $defOpt;
1237 }
1238
1239 $defOpt = $wgDefaultUserOptions;
1240 # default language setting
1241 $defOpt['variant'] = $wgContLang->getCode();
1242 $defOpt['language'] = $wgContLang->getCode();
1243 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1244 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1245 }
1246 $defOpt['skin'] = $wgDefaultSkin;
1247
1248 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1249
1250 return $defOpt;
1251 }
1252
1253 /**
1254 * Get a given default option value.
1255 *
1256 * @param $opt String Name of option to retrieve
1257 * @return String Default option value
1258 */
1259 public static function getDefaultOption( $opt ) {
1260 $defOpts = self::getDefaultOptions();
1261 if( isset( $defOpts[$opt] ) ) {
1262 return $defOpts[$opt];
1263 } else {
1264 return null;
1265 }
1266 }
1267
1268
1269 /**
1270 * Get blocking information
1271 * @param $bFromSlave Bool Whether to check the slave database first. To
1272 * improve performance, non-critical checks are done
1273 * against slaves. Check when actually saving should be
1274 * done against master.
1275 */
1276 private function getBlockedStatus( $bFromSlave = true ) {
1277 global $wgProxyWhitelist, $wgUser;
1278
1279 if ( -1 != $this->mBlockedby ) {
1280 return;
1281 }
1282
1283 wfProfileIn( __METHOD__ );
1284 wfDebug( __METHOD__.": checking...\n" );
1285
1286 // Initialize data...
1287 // Otherwise something ends up stomping on $this->mBlockedby when
1288 // things get lazy-loaded later, causing false positive block hits
1289 // due to -1 !== 0. Probably session-related... Nothing should be
1290 // overwriting mBlockedby, surely?
1291 $this->load();
1292
1293 # We only need to worry about passing the IP address to the Block generator if the
1294 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1295 # know which IP address they're actually coming from
1296 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1297 $ip = $this->getRequest()->getIP();
1298 } else {
1299 $ip = null;
1300 }
1301
1302 # User/IP blocking
1303 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1304
1305 # Proxy blocking
1306 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1307 && !in_array( $ip, $wgProxyWhitelist ) )
1308 {
1309 # Local list
1310 if ( self::isLocallyBlockedProxy( $ip ) ) {
1311 $block = new Block;
1312 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1313 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1314 $block->setTarget( $ip );
1315 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1316 $block = new Block;
1317 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1318 $block->mReason = wfMessage( 'sorbsreason' )->text();
1319 $block->setTarget( $ip );
1320 }
1321 }
1322
1323 if ( $block instanceof Block ) {
1324 wfDebug( __METHOD__ . ": Found block.\n" );
1325 $this->mBlock = $block;
1326 $this->mBlockedby = $block->getByName();
1327 $this->mBlockreason = $block->mReason;
1328 $this->mHideName = $block->mHideName;
1329 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1330 } else {
1331 $this->mBlockedby = '';
1332 $this->mHideName = 0;
1333 $this->mAllowUsertalk = false;
1334 }
1335
1336 # Extensions
1337 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1338
1339 wfProfileOut( __METHOD__ );
1340 }
1341
1342 /**
1343 * Whether the given IP is in a DNS blacklist.
1344 *
1345 * @param $ip String IP to check
1346 * @param $checkWhitelist Bool: whether to check the whitelist first
1347 * @return Bool True if blacklisted.
1348 */
1349 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1350 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1351 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1352
1353 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1354 return false;
1355
1356 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1357 return false;
1358
1359 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1360 return $this->inDnsBlacklist( $ip, $urls );
1361 }
1362
1363 /**
1364 * Whether the given IP is in a given DNS blacklist.
1365 *
1366 * @param $ip String IP to check
1367 * @param $bases String|Array of Strings: URL of the DNS blacklist
1368 * @return Bool True if blacklisted.
1369 */
1370 public function inDnsBlacklist( $ip, $bases ) {
1371 wfProfileIn( __METHOD__ );
1372
1373 $found = false;
1374 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1375 if( IP::isIPv4( $ip ) ) {
1376 # Reverse IP, bug 21255
1377 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1378
1379 foreach( (array)$bases as $base ) {
1380 # Make hostname
1381 # If we have an access key, use that too (ProjectHoneypot, etc.)
1382 if( is_array( $base ) ) {
1383 if( count( $base ) >= 2 ) {
1384 # Access key is 1, base URL is 0
1385 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1386 } else {
1387 $host = "$ipReversed.{$base[0]}";
1388 }
1389 } else {
1390 $host = "$ipReversed.$base";
1391 }
1392
1393 # Send query
1394 $ipList = gethostbynamel( $host );
1395
1396 if( $ipList ) {
1397 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1398 $found = true;
1399 break;
1400 } else {
1401 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1402 }
1403 }
1404 }
1405
1406 wfProfileOut( __METHOD__ );
1407 return $found;
1408 }
1409
1410 /**
1411 * Check if an IP address is in the local proxy list
1412 *
1413 * @param $ip string
1414 *
1415 * @return bool
1416 */
1417 public static function isLocallyBlockedProxy( $ip ) {
1418 global $wgProxyList;
1419
1420 if ( !$wgProxyList ) {
1421 return false;
1422 }
1423 wfProfileIn( __METHOD__ );
1424
1425 if ( !is_array( $wgProxyList ) ) {
1426 # Load from the specified file
1427 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1428 }
1429
1430 if ( !is_array( $wgProxyList ) ) {
1431 $ret = false;
1432 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1433 $ret = true;
1434 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1435 # Old-style flipped proxy list
1436 $ret = true;
1437 } else {
1438 $ret = false;
1439 }
1440 wfProfileOut( __METHOD__ );
1441 return $ret;
1442 }
1443
1444 /**
1445 * Is this user subject to rate limiting?
1446 *
1447 * @return Bool True if rate limited
1448 */
1449 public function isPingLimitable() {
1450 global $wgRateLimitsExcludedIPs;
1451 if( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1452 // No other good way currently to disable rate limits
1453 // for specific IPs. :P
1454 // But this is a crappy hack and should die.
1455 return false;
1456 }
1457 return !$this->isAllowed( 'noratelimit' );
1458 }
1459
1460 /**
1461 * Primitive rate limits: enforce maximum actions per time period
1462 * to put a brake on flooding.
1463 *
1464 * @note When using a shared cache like memcached, IP-address
1465 * last-hit counters will be shared across wikis.
1466 *
1467 * @param $action String Action to enforce; 'edit' if unspecified
1468 * @return Bool True if a rate limiter was tripped
1469 */
1470 public function pingLimiter( $action = 'edit' ) {
1471 # Call the 'PingLimiter' hook
1472 $result = false;
1473 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1474 return $result;
1475 }
1476
1477 global $wgRateLimits;
1478 if( !isset( $wgRateLimits[$action] ) ) {
1479 return false;
1480 }
1481
1482 # Some groups shouldn't trigger the ping limiter, ever
1483 if( !$this->isPingLimitable() )
1484 return false;
1485
1486 global $wgMemc, $wgRateLimitLog;
1487 wfProfileIn( __METHOD__ );
1488
1489 $limits = $wgRateLimits[$action];
1490 $keys = array();
1491 $id = $this->getId();
1492 $ip = $this->getRequest()->getIP();
1493 $userLimit = false;
1494
1495 if( isset( $limits['anon'] ) && $id == 0 ) {
1496 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1497 }
1498
1499 if( isset( $limits['user'] ) && $id != 0 ) {
1500 $userLimit = $limits['user'];
1501 }
1502 if( $this->isNewbie() ) {
1503 if( isset( $limits['newbie'] ) && $id != 0 ) {
1504 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1505 }
1506 if( isset( $limits['ip'] ) ) {
1507 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1508 }
1509 $matches = array();
1510 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1511 $subnet = $matches[1];
1512 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1513 }
1514 }
1515 // Check for group-specific permissions
1516 // If more than one group applies, use the group with the highest limit
1517 foreach ( $this->getGroups() as $group ) {
1518 if ( isset( $limits[$group] ) ) {
1519 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1520 $userLimit = $limits[$group];
1521 }
1522 }
1523 }
1524 // Set the user limit key
1525 if ( $userLimit !== false ) {
1526 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1527 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1528 }
1529
1530 $triggered = false;
1531 foreach( $keys as $key => $limit ) {
1532 list( $max, $period ) = $limit;
1533 $summary = "(limit $max in {$period}s)";
1534 $count = $wgMemc->get( $key );
1535 // Already pinged?
1536 if( $count ) {
1537 if( $count >= $max ) {
1538 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1539 if( $wgRateLimitLog ) {
1540 wfSuppressWarnings();
1541 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1542 wfRestoreWarnings();
1543 }
1544 $triggered = true;
1545 } else {
1546 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1547 }
1548 } else {
1549 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1550 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1551 }
1552 $wgMemc->incr( $key );
1553 }
1554
1555 wfProfileOut( __METHOD__ );
1556 return $triggered;
1557 }
1558
1559 /**
1560 * Check if user is blocked
1561 *
1562 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1563 * @return Bool True if blocked, false otherwise
1564 */
1565 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1566 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1567 }
1568
1569 /**
1570 * Get the block affecting the user, or null if the user is not blocked
1571 *
1572 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1573 * @return Block|null
1574 */
1575 public function getBlock( $bFromSlave = true ) {
1576 $this->getBlockedStatus( $bFromSlave );
1577 return $this->mBlock instanceof Block ? $this->mBlock : null;
1578 }
1579
1580 /**
1581 * Check if user is blocked from editing a particular article
1582 *
1583 * @param $title Title to check
1584 * @param $bFromSlave Bool whether to check the slave database instead of the master
1585 * @return Bool
1586 */
1587 function isBlockedFrom( $title, $bFromSlave = false ) {
1588 global $wgBlockAllowsUTEdit;
1589 wfProfileIn( __METHOD__ );
1590
1591 $blocked = $this->isBlocked( $bFromSlave );
1592 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1593 # If a user's name is suppressed, they cannot make edits anywhere
1594 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1595 $title->getNamespace() == NS_USER_TALK ) {
1596 $blocked = false;
1597 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1598 }
1599
1600 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1601
1602 wfProfileOut( __METHOD__ );
1603 return $blocked;
1604 }
1605
1606 /**
1607 * If user is blocked, return the name of the user who placed the block
1608 * @return String name of blocker
1609 */
1610 public function blockedBy() {
1611 $this->getBlockedStatus();
1612 return $this->mBlockedby;
1613 }
1614
1615 /**
1616 * If user is blocked, return the specified reason for the block
1617 * @return String Blocking reason
1618 */
1619 public function blockedFor() {
1620 $this->getBlockedStatus();
1621 return $this->mBlockreason;
1622 }
1623
1624 /**
1625 * If user is blocked, return the ID for the block
1626 * @return Int Block ID
1627 */
1628 public function getBlockId() {
1629 $this->getBlockedStatus();
1630 return ( $this->mBlock ? $this->mBlock->getId() : false );
1631 }
1632
1633 /**
1634 * Check if user is blocked on all wikis.
1635 * Do not use for actual edit permission checks!
1636 * This is intented for quick UI checks.
1637 *
1638 * @param $ip String IP address, uses current client if none given
1639 * @return Bool True if blocked, false otherwise
1640 */
1641 public function isBlockedGlobally( $ip = '' ) {
1642 if( $this->mBlockedGlobally !== null ) {
1643 return $this->mBlockedGlobally;
1644 }
1645 // User is already an IP?
1646 if( IP::isIPAddress( $this->getName() ) ) {
1647 $ip = $this->getName();
1648 } elseif( !$ip ) {
1649 $ip = $this->getRequest()->getIP();
1650 }
1651 $blocked = false;
1652 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1653 $this->mBlockedGlobally = (bool)$blocked;
1654 return $this->mBlockedGlobally;
1655 }
1656
1657 /**
1658 * Check if user account is locked
1659 *
1660 * @return Bool True if locked, false otherwise
1661 */
1662 public function isLocked() {
1663 if( $this->mLocked !== null ) {
1664 return $this->mLocked;
1665 }
1666 global $wgAuth;
1667 $authUser = $wgAuth->getUserInstance( $this );
1668 $this->mLocked = (bool)$authUser->isLocked();
1669 return $this->mLocked;
1670 }
1671
1672 /**
1673 * Check if user account is hidden
1674 *
1675 * @return Bool True if hidden, false otherwise
1676 */
1677 public function isHidden() {
1678 if( $this->mHideName !== null ) {
1679 return $this->mHideName;
1680 }
1681 $this->getBlockedStatus();
1682 if( !$this->mHideName ) {
1683 global $wgAuth;
1684 $authUser = $wgAuth->getUserInstance( $this );
1685 $this->mHideName = (bool)$authUser->isHidden();
1686 }
1687 return $this->mHideName;
1688 }
1689
1690 /**
1691 * Get the user's ID.
1692 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1693 */
1694 public function getId() {
1695 if( $this->mId === null && $this->mName !== null
1696 && User::isIP( $this->mName ) ) {
1697 // Special case, we know the user is anonymous
1698 return 0;
1699 } elseif( !$this->isItemLoaded( 'id' ) ) {
1700 // Don't load if this was initialized from an ID
1701 $this->load();
1702 }
1703 return $this->mId;
1704 }
1705
1706 /**
1707 * Set the user and reload all fields according to a given ID
1708 * @param $v Int User ID to reload
1709 */
1710 public function setId( $v ) {
1711 $this->mId = $v;
1712 $this->clearInstanceCache( 'id' );
1713 }
1714
1715 /**
1716 * Get the user name, or the IP of an anonymous user
1717 * @return String User's name or IP address
1718 */
1719 public function getName() {
1720 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1721 # Special case optimisation
1722 return $this->mName;
1723 } else {
1724 $this->load();
1725 if ( $this->mName === false ) {
1726 # Clean up IPs
1727 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1728 }
1729 return $this->mName;
1730 }
1731 }
1732
1733 /**
1734 * Set the user name.
1735 *
1736 * This does not reload fields from the database according to the given
1737 * name. Rather, it is used to create a temporary "nonexistent user" for
1738 * later addition to the database. It can also be used to set the IP
1739 * address for an anonymous user to something other than the current
1740 * remote IP.
1741 *
1742 * @note User::newFromName() has rougly the same function, when the named user
1743 * does not exist.
1744 * @param $str String New user name to set
1745 */
1746 public function setName( $str ) {
1747 $this->load();
1748 $this->mName = $str;
1749 }
1750
1751 /**
1752 * Get the user's name escaped by underscores.
1753 * @return String Username escaped by underscores.
1754 */
1755 public function getTitleKey() {
1756 return str_replace( ' ', '_', $this->getName() );
1757 }
1758
1759 /**
1760 * Check if the user has new messages.
1761 * @return Bool True if the user has new messages
1762 */
1763 public function getNewtalk() {
1764 $this->load();
1765
1766 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1767 if( $this->mNewtalk === -1 ) {
1768 $this->mNewtalk = false; # reset talk page status
1769
1770 # Check memcached separately for anons, who have no
1771 # entire User object stored in there.
1772 if( !$this->mId ) {
1773 global $wgDisableAnonTalk;
1774 if( $wgDisableAnonTalk ) {
1775 // Anon newtalk disabled by configuration.
1776 $this->mNewtalk = false;
1777 } else {
1778 global $wgMemc;
1779 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1780 $newtalk = $wgMemc->get( $key );
1781 if( strval( $newtalk ) !== '' ) {
1782 $this->mNewtalk = (bool)$newtalk;
1783 } else {
1784 // Since we are caching this, make sure it is up to date by getting it
1785 // from the master
1786 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1787 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1788 }
1789 }
1790 } else {
1791 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1792 }
1793 }
1794
1795 return (bool)$this->mNewtalk;
1796 }
1797
1798 /**
1799 * Return the talk page(s) this user has new messages on.
1800 * @return Array of String page URLs
1801 */
1802 public function getNewMessageLinks() {
1803 $talks = array();
1804 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1805 return $talks;
1806 } elseif( !$this->getNewtalk() ) {
1807 return array();
1808 }
1809 $utp = $this->getTalkPage();
1810 $dbr = wfGetDB( DB_SLAVE );
1811 // Get the "last viewed rev" timestamp from the oldest message notification
1812 $timestamp = $dbr->selectField( 'user_newtalk',
1813 'MIN(user_last_timestamp)',
1814 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1815 __METHOD__ );
1816 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1817 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1818 }
1819
1820 /**
1821 * Internal uncached check for new messages
1822 *
1823 * @see getNewtalk()
1824 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1825 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1826 * @param $fromMaster Bool true to fetch from the master, false for a slave
1827 * @return Bool True if the user has new messages
1828 */
1829 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1830 if ( $fromMaster ) {
1831 $db = wfGetDB( DB_MASTER );
1832 } else {
1833 $db = wfGetDB( DB_SLAVE );
1834 }
1835 $ok = $db->selectField( 'user_newtalk', $field,
1836 array( $field => $id ), __METHOD__ );
1837 return $ok !== false;
1838 }
1839
1840 /**
1841 * Add or update the new messages flag
1842 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1843 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1844 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1845 * @return Bool True if successful, false otherwise
1846 */
1847 protected function updateNewtalk( $field, $id, $curRev = null ) {
1848 // Get timestamp of the talk page revision prior to the current one
1849 $prevRev = $curRev ? $curRev->getPrevious() : false;
1850 $ts = $prevRev ? $prevRev->getTimestamp() : null;
1851 // Mark the user as having new messages since this revision
1852 $dbw = wfGetDB( DB_MASTER );
1853 $dbw->insert( 'user_newtalk',
1854 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1855 __METHOD__,
1856 'IGNORE' );
1857 if ( $dbw->affectedRows() ) {
1858 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1859 return true;
1860 } else {
1861 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1862 return false;
1863 }
1864 }
1865
1866 /**
1867 * Clear the new messages flag for the given user
1868 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1869 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1870 * @return Bool True if successful, false otherwise
1871 */
1872 protected function deleteNewtalk( $field, $id ) {
1873 $dbw = wfGetDB( DB_MASTER );
1874 $dbw->delete( 'user_newtalk',
1875 array( $field => $id ),
1876 __METHOD__ );
1877 if ( $dbw->affectedRows() ) {
1878 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1879 return true;
1880 } else {
1881 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1882 return false;
1883 }
1884 }
1885
1886 /**
1887 * Update the 'You have new messages!' status.
1888 * @param $val Bool Whether the user has new messages
1889 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1890 */
1891 public function setNewtalk( $val, $curRev = null ) {
1892 if( wfReadOnly() ) {
1893 return;
1894 }
1895
1896 $this->load();
1897 $this->mNewtalk = $val;
1898
1899 if( $this->isAnon() ) {
1900 $field = 'user_ip';
1901 $id = $this->getName();
1902 } else {
1903 $field = 'user_id';
1904 $id = $this->getId();
1905 }
1906 global $wgMemc;
1907
1908 if( $val ) {
1909 $changed = $this->updateNewtalk( $field, $id, $curRev );
1910 } else {
1911 $changed = $this->deleteNewtalk( $field, $id );
1912 }
1913
1914 if( $this->isAnon() ) {
1915 // Anons have a separate memcached space, since
1916 // user records aren't kept for them.
1917 $key = wfMemcKey( 'newtalk', 'ip', $id );
1918 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1919 }
1920 if ( $changed ) {
1921 $this->invalidateCache();
1922 }
1923 }
1924
1925 /**
1926 * Generate a current or new-future timestamp to be stored in the
1927 * user_touched field when we update things.
1928 * @return String Timestamp in TS_MW format
1929 */
1930 private static function newTouchedTimestamp() {
1931 global $wgClockSkewFudge;
1932 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1933 }
1934
1935 /**
1936 * Clear user data from memcached.
1937 * Use after applying fun updates to the database; caller's
1938 * responsibility to update user_touched if appropriate.
1939 *
1940 * Called implicitly from invalidateCache() and saveSettings().
1941 */
1942 private function clearSharedCache() {
1943 $this->load();
1944 if( $this->mId ) {
1945 global $wgMemc;
1946 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1947 }
1948 }
1949
1950 /**
1951 * Immediately touch the user data cache for this account.
1952 * Updates user_touched field, and removes account data from memcached
1953 * for reload on the next hit.
1954 */
1955 public function invalidateCache() {
1956 if( wfReadOnly() ) {
1957 return;
1958 }
1959 $this->load();
1960 if( $this->mId ) {
1961 $this->mTouched = self::newTouchedTimestamp();
1962
1963 $dbw = wfGetDB( DB_MASTER );
1964
1965 // Prevent contention slams by checking user_touched first
1966 $now = $dbw->timestamp( $this->mTouched );
1967 $needsPurge = $dbw->selectField( 'user', '1',
1968 array( 'user_id' => $this->mId, 'user_touched < ' . $dbw->addQuotes( $now ) )
1969 );
1970 if ( $needsPurge ) {
1971 $dbw->update( 'user',
1972 array( 'user_touched' => $now ),
1973 array( 'user_id' => $this->mId, 'user_touched < ' . $dbw->addQuotes( $now ) ),
1974 __METHOD__
1975 );
1976 }
1977
1978 $this->clearSharedCache();
1979 }
1980 }
1981
1982 /**
1983 * Validate the cache for this account.
1984 * @param $timestamp String A timestamp in TS_MW format
1985 *
1986 * @return bool
1987 */
1988 public function validateCache( $timestamp ) {
1989 $this->load();
1990 return ( $timestamp >= $this->mTouched );
1991 }
1992
1993 /**
1994 * Get the user touched timestamp
1995 * @return String timestamp
1996 */
1997 public function getTouched() {
1998 $this->load();
1999 return $this->mTouched;
2000 }
2001
2002 /**
2003 * Set the password and reset the random token.
2004 * Calls through to authentication plugin if necessary;
2005 * will have no effect if the auth plugin refuses to
2006 * pass the change through or if the legal password
2007 * checks fail.
2008 *
2009 * As a special case, setting the password to null
2010 * wipes it, so the account cannot be logged in until
2011 * a new password is set, for instance via e-mail.
2012 *
2013 * @param $str String New password to set
2014 * @throws PasswordError on failure
2015 *
2016 * @return bool
2017 */
2018 public function setPassword( $str ) {
2019 global $wgAuth;
2020
2021 if( $str !== null ) {
2022 if( !$wgAuth->allowPasswordChange() ) {
2023 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2024 }
2025
2026 if( !$this->isValidPassword( $str ) ) {
2027 global $wgMinimalPasswordLength;
2028 $valid = $this->getPasswordValidity( $str );
2029 if ( is_array( $valid ) ) {
2030 $message = array_shift( $valid );
2031 $params = $valid;
2032 } else {
2033 $message = $valid;
2034 $params = array( $wgMinimalPasswordLength );
2035 }
2036 throw new PasswordError( wfMessage( $message, $params )->text() );
2037 }
2038 }
2039
2040 if( !$wgAuth->setPassword( $this, $str ) ) {
2041 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2042 }
2043
2044 $this->setInternalPassword( $str );
2045
2046 return true;
2047 }
2048
2049 /**
2050 * Set the password and reset the random token unconditionally.
2051 *
2052 * @param $str string|null New password to set or null to set an invalid
2053 * password hash meaning that the user will not be able to log in
2054 * through the web interface.
2055 */
2056 public function setInternalPassword( $str ) {
2057 $this->load();
2058 $this->setToken();
2059
2060 if( $str === null ) {
2061 // Save an invalid hash...
2062 $this->mPassword = '';
2063 } else {
2064 $this->mPassword = self::crypt( $str );
2065 }
2066 $this->mNewpassword = '';
2067 $this->mNewpassTime = null;
2068 }
2069
2070 /**
2071 * Get the user's current token.
2072 * @param $forceCreation bool Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2073 * @return String Token
2074 */
2075 public function getToken( $forceCreation = true ) {
2076 $this->load();
2077 if ( !$this->mToken && $forceCreation ) {
2078 $this->setToken();
2079 }
2080 return $this->mToken;
2081 }
2082
2083 /**
2084 * Set the random token (used for persistent authentication)
2085 * Called from loadDefaults() among other places.
2086 *
2087 * @param $token String|bool If specified, set the token to this value
2088 */
2089 public function setToken( $token = false ) {
2090 $this->load();
2091 if ( !$token ) {
2092 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2093 } else {
2094 $this->mToken = $token;
2095 }
2096 }
2097
2098 /**
2099 * Set the password for a password reminder or new account email
2100 *
2101 * @param $str String New password to set
2102 * @param $throttle Bool If true, reset the throttle timestamp to the present
2103 */
2104 public function setNewpassword( $str, $throttle = true ) {
2105 $this->load();
2106 $this->mNewpassword = self::crypt( $str );
2107 if ( $throttle ) {
2108 $this->mNewpassTime = wfTimestampNow();
2109 }
2110 }
2111
2112 /**
2113 * Has password reminder email been sent within the last
2114 * $wgPasswordReminderResendTime hours?
2115 * @return Bool
2116 */
2117 public function isPasswordReminderThrottled() {
2118 global $wgPasswordReminderResendTime;
2119 $this->load();
2120 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2121 return false;
2122 }
2123 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2124 return time() < $expiry;
2125 }
2126
2127 /**
2128 * Get the user's e-mail address
2129 * @return String User's email address
2130 */
2131 public function getEmail() {
2132 $this->load();
2133 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2134 return $this->mEmail;
2135 }
2136
2137 /**
2138 * Get the timestamp of the user's e-mail authentication
2139 * @return String TS_MW timestamp
2140 */
2141 public function getEmailAuthenticationTimestamp() {
2142 $this->load();
2143 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2144 return $this->mEmailAuthenticated;
2145 }
2146
2147 /**
2148 * Set the user's e-mail address
2149 * @param $str String New e-mail address
2150 */
2151 public function setEmail( $str ) {
2152 $this->load();
2153 if( $str == $this->mEmail ) {
2154 return;
2155 }
2156 $this->mEmail = $str;
2157 $this->invalidateEmail();
2158 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2159 }
2160
2161 /**
2162 * Set the user's e-mail address and a confirmation mail if needed.
2163 *
2164 * @since 1.20
2165 * @param $str String New e-mail address
2166 * @return Status
2167 */
2168 public function setEmailWithConfirmation( $str ) {
2169 global $wgEnableEmail, $wgEmailAuthentication;
2170
2171 if ( !$wgEnableEmail ) {
2172 return Status::newFatal( 'emaildisabled' );
2173 }
2174
2175 $oldaddr = $this->getEmail();
2176 if ( $str === $oldaddr ) {
2177 return Status::newGood( true );
2178 }
2179
2180 $this->setEmail( $str );
2181
2182 if ( $str !== '' && $wgEmailAuthentication ) {
2183 # Send a confirmation request to the new address if needed
2184 $type = $oldaddr != '' ? 'changed' : 'set';
2185 $result = $this->sendConfirmationMail( $type );
2186 if ( $result->isGood() ) {
2187 # Say the the caller that a confirmation mail has been sent
2188 $result->value = 'eauth';
2189 }
2190 } else {
2191 $result = Status::newGood( true );
2192 }
2193
2194 return $result;
2195 }
2196
2197 /**
2198 * Get the user's real name
2199 * @return String User's real name
2200 */
2201 public function getRealName() {
2202 if ( !$this->isItemLoaded( 'realname' ) ) {
2203 $this->load();
2204 }
2205
2206 return $this->mRealName;
2207 }
2208
2209 /**
2210 * Set the user's real name
2211 * @param $str String New real name
2212 */
2213 public function setRealName( $str ) {
2214 $this->load();
2215 $this->mRealName = $str;
2216 }
2217
2218 /**
2219 * Get the user's current setting for a given option.
2220 *
2221 * @param $oname String The option to check
2222 * @param $defaultOverride String A default value returned if the option does not exist
2223 * @param $ignoreHidden Bool = whether to ignore the effects of $wgHiddenPrefs
2224 * @return String User's current value for the option
2225 * @see getBoolOption()
2226 * @see getIntOption()
2227 */
2228 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2229 global $wgHiddenPrefs;
2230 $this->loadOptions();
2231
2232 # We want 'disabled' preferences to always behave as the default value for
2233 # users, even if they have set the option explicitly in their settings (ie they
2234 # set it, and then it was disabled removing their ability to change it). But
2235 # we don't want to erase the preferences in the database in case the preference
2236 # is re-enabled again. So don't touch $mOptions, just override the returned value
2237 if( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) {
2238 return self::getDefaultOption( $oname );
2239 }
2240
2241 if ( array_key_exists( $oname, $this->mOptions ) ) {
2242 return $this->mOptions[$oname];
2243 } else {
2244 return $defaultOverride;
2245 }
2246 }
2247
2248 /**
2249 * Get all user's options
2250 *
2251 * @return array
2252 */
2253 public function getOptions() {
2254 global $wgHiddenPrefs;
2255 $this->loadOptions();
2256 $options = $this->mOptions;
2257
2258 # We want 'disabled' preferences to always behave as the default value for
2259 # users, even if they have set the option explicitly in their settings (ie they
2260 # set it, and then it was disabled removing their ability to change it). But
2261 # we don't want to erase the preferences in the database in case the preference
2262 # is re-enabled again. So don't touch $mOptions, just override the returned value
2263 foreach( $wgHiddenPrefs as $pref ) {
2264 $default = self::getDefaultOption( $pref );
2265 if( $default !== null ) {
2266 $options[$pref] = $default;
2267 }
2268 }
2269
2270 return $options;
2271 }
2272
2273 /**
2274 * Get the user's current setting for a given option, as a boolean value.
2275 *
2276 * @param $oname String The option to check
2277 * @return Bool User's current value for the option
2278 * @see getOption()
2279 */
2280 public function getBoolOption( $oname ) {
2281 return (bool)$this->getOption( $oname );
2282 }
2283
2284 /**
2285 * Get the user's current setting for a given option, as a boolean value.
2286 *
2287 * @param $oname String The option to check
2288 * @param $defaultOverride Int A default value returned if the option does not exist
2289 * @return Int User's current value for the option
2290 * @see getOption()
2291 */
2292 public function getIntOption( $oname, $defaultOverride = 0 ) {
2293 $val = $this->getOption( $oname );
2294 if( $val == '' ) {
2295 $val = $defaultOverride;
2296 }
2297 return intval( $val );
2298 }
2299
2300 /**
2301 * Set the given option for a user.
2302 *
2303 * @param $oname String The option to set
2304 * @param $val mixed New value to set
2305 */
2306 public function setOption( $oname, $val ) {
2307 $this->loadOptions();
2308
2309 // Explicitly NULL values should refer to defaults
2310 if( is_null( $val ) ) {
2311 $val = self::getDefaultOption( $oname );
2312 }
2313
2314 $this->mOptions[$oname] = $val;
2315 }
2316
2317 /**
2318 * Return a list of the types of user options currently returned by
2319 * User::getOptionKinds().
2320 *
2321 * Currently, the option kinds are:
2322 * - 'registered' - preferences which are registered in core MediaWiki or
2323 * by extensions using the UserGetDefaultOptions hook.
2324 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2325 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2326 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2327 * be used by user scripts.
2328 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2329 * These are usually legacy options, removed in newer versions.
2330 *
2331 * The API (and possibly others) use this function to determine the possible
2332 * option types for validation purposes, so make sure to update this when a
2333 * new option kind is added.
2334 *
2335 * @see User::getOptionKinds
2336 * @return array Option kinds
2337 */
2338 public static function listOptionKinds() {
2339 return array(
2340 'registered',
2341 'registered-multiselect',
2342 'registered-checkmatrix',
2343 'userjs',
2344 'unused'
2345 );
2346 }
2347
2348 /**
2349 * Return an associative array mapping preferences keys to the kind of a preference they're
2350 * used for. Different kinds are handled differently when setting or reading preferences.
2351 *
2352 * See User::listOptionKinds for the list of valid option types that can be provided.
2353 *
2354 * @see User::listOptionKinds
2355 * @param $context IContextSource
2356 * @param $options array assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2357 * @return array the key => kind mapping data
2358 */
2359 public function getOptionKinds( IContextSource $context, $options = null ) {
2360 $this->loadOptions();
2361 if ( $options === null ) {
2362 $options = $this->mOptions;
2363 }
2364
2365 $prefs = Preferences::getPreferences( $this, $context );
2366 $mapping = array();
2367
2368 // Multiselect and checkmatrix options are stored in the database with
2369 // one key per option, each having a boolean value. Extract those keys.
2370 $multiselectOptions = array();
2371 foreach ( $prefs as $name => $info ) {
2372 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2373 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2374 $opts = HTMLFormField::flattenOptions( $info['options'] );
2375 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2376
2377 foreach ( $opts as $value ) {
2378 $multiselectOptions["$prefix$value"] = true;
2379 }
2380
2381 unset( $prefs[$name] );
2382 }
2383 }
2384 $checkmatrixOptions = array();
2385 foreach ( $prefs as $name => $info ) {
2386 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2387 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2388 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2389 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2390 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2391
2392 foreach ( $columns as $column ) {
2393 foreach ( $rows as $row ) {
2394 $checkmatrixOptions["$prefix-$column-$row"] = true;
2395 }
2396 }
2397
2398 unset( $prefs[$name] );
2399 }
2400 }
2401
2402 // $value is ignored
2403 foreach ( $options as $key => $value ) {
2404 if ( isset( $prefs[$key] ) ) {
2405 $mapping[$key] = 'registered';
2406 } elseif( isset( $multiselectOptions[$key] ) ) {
2407 $mapping[$key] = 'registered-multiselect';
2408 } elseif( isset( $checkmatrixOptions[$key] ) ) {
2409 $mapping[$key] = 'registered-checkmatrix';
2410 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2411 $mapping[$key] = 'userjs';
2412 } else {
2413 $mapping[$key] = 'unused';
2414 }
2415 }
2416
2417 return $mapping;
2418 }
2419
2420 /**
2421 * Reset certain (or all) options to the site defaults
2422 *
2423 * The optional parameter determines which kinds of preferences will be reset.
2424 * Supported values are everything that can be reported by getOptionKinds()
2425 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2426 *
2427 * @param $resetKinds array|string which kinds of preferences to reset. Defaults to
2428 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2429 * for backwards-compatibility.
2430 * @param $context IContextSource|null context source used when $resetKinds
2431 * does not contain 'all', passed to getOptionKinds().
2432 * Defaults to RequestContext::getMain() when null.
2433 */
2434 public function resetOptions(
2435 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2436 IContextSource $context = null
2437 ) {
2438 $this->load();
2439 $defaultOptions = self::getDefaultOptions();
2440
2441 if ( !is_array( $resetKinds ) ) {
2442 $resetKinds = array( $resetKinds );
2443 }
2444
2445 if ( in_array( 'all', $resetKinds ) ) {
2446 $newOptions = $defaultOptions;
2447 } else {
2448 if ( $context === null ) {
2449 $context = RequestContext::getMain();
2450 }
2451
2452 $optionKinds = $this->getOptionKinds( $context );
2453 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2454 $newOptions = array();
2455
2456 // Use default values for the options that should be deleted, and
2457 // copy old values for the ones that shouldn't.
2458 foreach ( $this->mOptions as $key => $value ) {
2459 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2460 if ( array_key_exists( $key, $defaultOptions ) ) {
2461 $newOptions[$key] = $defaultOptions[$key];
2462 }
2463 } else {
2464 $newOptions[$key] = $value;
2465 }
2466 }
2467 }
2468
2469 $this->mOptions = $newOptions;
2470 $this->mOptionsLoaded = true;
2471 }
2472
2473 /**
2474 * Get the user's preferred date format.
2475 * @return String User's preferred date format
2476 */
2477 public function getDatePreference() {
2478 // Important migration for old data rows
2479 if ( is_null( $this->mDatePreference ) ) {
2480 global $wgLang;
2481 $value = $this->getOption( 'date' );
2482 $map = $wgLang->getDatePreferenceMigrationMap();
2483 if ( isset( $map[$value] ) ) {
2484 $value = $map[$value];
2485 }
2486 $this->mDatePreference = $value;
2487 }
2488 return $this->mDatePreference;
2489 }
2490
2491 /**
2492 * Get the user preferred stub threshold
2493 *
2494 * @return int
2495 */
2496 public function getStubThreshold() {
2497 global $wgMaxArticleSize; # Maximum article size, in Kb
2498 $threshold = $this->getIntOption( 'stubthreshold' );
2499 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2500 # If they have set an impossible value, disable the preference
2501 # so we can use the parser cache again.
2502 $threshold = 0;
2503 }
2504 return $threshold;
2505 }
2506
2507 /**
2508 * Get the permissions this user has.
2509 * @return Array of String permission names
2510 */
2511 public function getRights() {
2512 if ( is_null( $this->mRights ) ) {
2513 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2514 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2515 // Force reindexation of rights when a hook has unset one of them
2516 $this->mRights = array_values( array_unique( $this->mRights ) );
2517 }
2518 return $this->mRights;
2519 }
2520
2521 /**
2522 * Get the list of explicit group memberships this user has.
2523 * The implicit * and user groups are not included.
2524 * @return Array of String internal group names
2525 */
2526 public function getGroups() {
2527 $this->load();
2528 $this->loadGroups();
2529 return $this->mGroups;
2530 }
2531
2532 /**
2533 * Get the list of implicit group memberships this user has.
2534 * This includes all explicit groups, plus 'user' if logged in,
2535 * '*' for all accounts, and autopromoted groups
2536 * @param $recache Bool Whether to avoid the cache
2537 * @return Array of String internal group names
2538 */
2539 public function getEffectiveGroups( $recache = false ) {
2540 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2541 wfProfileIn( __METHOD__ );
2542 $this->mEffectiveGroups = array_unique( array_merge(
2543 $this->getGroups(), // explicit groups
2544 $this->getAutomaticGroups( $recache ) // implicit groups
2545 ) );
2546 # Hook for additional groups
2547 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2548 // Force reindexation of groups when a hook has unset one of them
2549 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2550 wfProfileOut( __METHOD__ );
2551 }
2552 return $this->mEffectiveGroups;
2553 }
2554
2555 /**
2556 * Get the list of implicit group memberships this user has.
2557 * This includes 'user' if logged in, '*' for all accounts,
2558 * and autopromoted groups
2559 * @param $recache Bool Whether to avoid the cache
2560 * @return Array of String internal group names
2561 */
2562 public function getAutomaticGroups( $recache = false ) {
2563 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2564 wfProfileIn( __METHOD__ );
2565 $this->mImplicitGroups = array( '*' );
2566 if ( $this->getId() ) {
2567 $this->mImplicitGroups[] = 'user';
2568
2569 $this->mImplicitGroups = array_unique( array_merge(
2570 $this->mImplicitGroups,
2571 Autopromote::getAutopromoteGroups( $this )
2572 ) );
2573 }
2574 if ( $recache ) {
2575 # Assure data consistency with rights/groups,
2576 # as getEffectiveGroups() depends on this function
2577 $this->mEffectiveGroups = null;
2578 }
2579 wfProfileOut( __METHOD__ );
2580 }
2581 return $this->mImplicitGroups;
2582 }
2583
2584 /**
2585 * Returns the groups the user has belonged to.
2586 *
2587 * The user may still belong to the returned groups. Compare with getGroups().
2588 *
2589 * The function will not return groups the user had belonged to before MW 1.17
2590 *
2591 * @return array Names of the groups the user has belonged to.
2592 */
2593 public function getFormerGroups() {
2594 if( is_null( $this->mFormerGroups ) ) {
2595 $dbr = wfGetDB( DB_MASTER );
2596 $res = $dbr->select( 'user_former_groups',
2597 array( 'ufg_group' ),
2598 array( 'ufg_user' => $this->mId ),
2599 __METHOD__ );
2600 $this->mFormerGroups = array();
2601 foreach( $res as $row ) {
2602 $this->mFormerGroups[] = $row->ufg_group;
2603 }
2604 }
2605 return $this->mFormerGroups;
2606 }
2607
2608 /**
2609 * Get the user's edit count.
2610 * @return Int
2611 */
2612 public function getEditCount() {
2613 if ( !$this->getId() ) {
2614 return null;
2615 }
2616
2617 if ( !isset( $this->mEditCount ) ) {
2618 /* Populate the count, if it has not been populated yet */
2619 wfProfileIn( __METHOD__ );
2620 $dbr = wfGetDB( DB_SLAVE );
2621 // check if the user_editcount field has been initialized
2622 $count = $dbr->selectField(
2623 'user', 'user_editcount',
2624 array( 'user_id' => $this->mId ),
2625 __METHOD__
2626 );
2627
2628 if( $count === null ) {
2629 // it has not been initialized. do so.
2630 $count = $this->initEditCount();
2631 }
2632 $this->mEditCount = intval( $count );
2633 wfProfileOut( __METHOD__ );
2634 }
2635 return $this->mEditCount;
2636 }
2637
2638 /**
2639 * Add the user to the given group.
2640 * This takes immediate effect.
2641 * @param $group String Name of the group to add
2642 */
2643 public function addGroup( $group ) {
2644 if( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2645 $dbw = wfGetDB( DB_MASTER );
2646 if( $this->getId() ) {
2647 $dbw->insert( 'user_groups',
2648 array(
2649 'ug_user' => $this->getID(),
2650 'ug_group' => $group,
2651 ),
2652 __METHOD__,
2653 array( 'IGNORE' ) );
2654 }
2655 }
2656 $this->loadGroups();
2657 $this->mGroups[] = $group;
2658 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2659
2660 $this->invalidateCache();
2661 }
2662
2663 /**
2664 * Remove the user from the given group.
2665 * This takes immediate effect.
2666 * @param $group String Name of the group to remove
2667 */
2668 public function removeGroup( $group ) {
2669 $this->load();
2670 if( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2671 $dbw = wfGetDB( DB_MASTER );
2672 $dbw->delete( 'user_groups',
2673 array(
2674 'ug_user' => $this->getID(),
2675 'ug_group' => $group,
2676 ), __METHOD__ );
2677 // Remember that the user was in this group
2678 $dbw->insert( 'user_former_groups',
2679 array(
2680 'ufg_user' => $this->getID(),
2681 'ufg_group' => $group,
2682 ),
2683 __METHOD__,
2684 array( 'IGNORE' ) );
2685 }
2686 $this->loadGroups();
2687 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2688 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2689
2690 $this->invalidateCache();
2691 }
2692
2693 /**
2694 * Get whether the user is logged in
2695 * @return Bool
2696 */
2697 public function isLoggedIn() {
2698 return $this->getID() != 0;
2699 }
2700
2701 /**
2702 * Get whether the user is anonymous
2703 * @return Bool
2704 */
2705 public function isAnon() {
2706 return !$this->isLoggedIn();
2707 }
2708
2709 /**
2710 * Check if user is allowed to access a feature / make an action
2711 *
2712 * @internal param \String $varargs permissions to test
2713 * @return Boolean: True if user is allowed to perform *any* of the given actions
2714 *
2715 * @return bool
2716 */
2717 public function isAllowedAny( /*...*/ ) {
2718 $permissions = func_get_args();
2719 foreach( $permissions as $permission ) {
2720 if( $this->isAllowed( $permission ) ) {
2721 return true;
2722 }
2723 }
2724 return false;
2725 }
2726
2727 /**
2728 *
2729 * @internal param $varargs string
2730 * @return bool True if the user is allowed to perform *all* of the given actions
2731 */
2732 public function isAllowedAll( /*...*/ ) {
2733 $permissions = func_get_args();
2734 foreach( $permissions as $permission ) {
2735 if( !$this->isAllowed( $permission ) ) {
2736 return false;
2737 }
2738 }
2739 return true;
2740 }
2741
2742 /**
2743 * Internal mechanics of testing a permission
2744 * @param $action String
2745 * @return bool
2746 */
2747 public function isAllowed( $action = '' ) {
2748 if ( $action === '' ) {
2749 return true; // In the spirit of DWIM
2750 }
2751 # Patrolling may not be enabled
2752 if( $action === 'patrol' || $action === 'autopatrol' ) {
2753 global $wgUseRCPatrol, $wgUseNPPatrol;
2754 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2755 return false;
2756 }
2757 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2758 # by misconfiguration: 0 == 'foo'
2759 return in_array( $action, $this->getRights(), true );
2760 }
2761
2762 /**
2763 * Check whether to enable recent changes patrol features for this user
2764 * @return Boolean: True or false
2765 */
2766 public function useRCPatrol() {
2767 global $wgUseRCPatrol;
2768 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2769 }
2770
2771 /**
2772 * Check whether to enable new pages patrol features for this user
2773 * @return Bool True or false
2774 */
2775 public function useNPPatrol() {
2776 global $wgUseRCPatrol, $wgUseNPPatrol;
2777 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) );
2778 }
2779
2780 /**
2781 * Get the WebRequest object to use with this object
2782 *
2783 * @return WebRequest
2784 */
2785 public function getRequest() {
2786 if ( $this->mRequest ) {
2787 return $this->mRequest;
2788 } else {
2789 global $wgRequest;
2790 return $wgRequest;
2791 }
2792 }
2793
2794 /**
2795 * Get the current skin, loading it if required
2796 * @return Skin The current skin
2797 * @todo FIXME: Need to check the old failback system [AV]
2798 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2799 */
2800 public function getSkin() {
2801 wfDeprecated( __METHOD__, '1.18' );
2802 return RequestContext::getMain()->getSkin();
2803 }
2804
2805 /**
2806 * Get a WatchedItem for this user and $title.
2807 *
2808 * @param $title Title
2809 * @return WatchedItem
2810 */
2811 public function getWatchedItem( $title ) {
2812 $key = $title->getNamespace() . ':' . $title->getDBkey();
2813
2814 if ( isset( $this->mWatchedItems[$key] ) ) {
2815 return $this->mWatchedItems[$key];
2816 }
2817
2818 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
2819 $this->mWatchedItems = array();
2820 }
2821
2822 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title );
2823 return $this->mWatchedItems[$key];
2824 }
2825
2826 /**
2827 * Check the watched status of an article.
2828 * @param $title Title of the article to look at
2829 * @return Bool
2830 */
2831 public function isWatched( $title ) {
2832 return $this->getWatchedItem( $title )->isWatched();
2833 }
2834
2835 /**
2836 * Watch an article.
2837 * @param $title Title of the article to look at
2838 */
2839 public function addWatch( $title ) {
2840 $this->getWatchedItem( $title )->addWatch();
2841 $this->invalidateCache();
2842 }
2843
2844 /**
2845 * Stop watching an article.
2846 * @param $title Title of the article to look at
2847 */
2848 public function removeWatch( $title ) {
2849 $this->getWatchedItem( $title )->removeWatch();
2850 $this->invalidateCache();
2851 }
2852
2853 /**
2854 * Clear the user's notification timestamp for the given title.
2855 * If e-notif e-mails are on, they will receive notification mails on
2856 * the next change of the page if it's watched etc.
2857 * @param $title Title of the article to look at
2858 */
2859 public function clearNotification( &$title ) {
2860 global $wgUseEnotif, $wgShowUpdatedMarker;
2861
2862 # Do nothing if the database is locked to writes
2863 if( wfReadOnly() ) {
2864 return;
2865 }
2866
2867 if( $title->getNamespace() == NS_USER_TALK &&
2868 $title->getText() == $this->getName() ) {
2869 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2870 return;
2871 $this->setNewtalk( false );
2872 }
2873
2874 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2875 return;
2876 }
2877
2878 if( $this->isAnon() ) {
2879 // Nothing else to do...
2880 return;
2881 }
2882
2883 // Only update the timestamp if the page is being watched.
2884 // The query to find out if it is watched is cached both in memcached and per-invocation,
2885 // and when it does have to be executed, it can be on a slave
2886 // If this is the user's newtalk page, we always update the timestamp
2887 $force = '';
2888 if ( $title->getNamespace() == NS_USER_TALK &&
2889 $title->getText() == $this->getName() )
2890 {
2891 $force = 'force';
2892 }
2893
2894 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
2895 }
2896
2897 /**
2898 * Resets all of the given user's page-change notification timestamps.
2899 * If e-notif e-mails are on, they will receive notification mails on
2900 * the next change of any watched page.
2901 */
2902 public function clearAllNotifications() {
2903 if ( wfReadOnly() ) {
2904 return;
2905 }
2906
2907 global $wgUseEnotif, $wgShowUpdatedMarker;
2908 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2909 $this->setNewtalk( false );
2910 return;
2911 }
2912 $id = $this->getId();
2913 if( $id != 0 ) {
2914 $dbw = wfGetDB( DB_MASTER );
2915 $dbw->update( 'watchlist',
2916 array( /* SET */
2917 'wl_notificationtimestamp' => null
2918 ), array( /* WHERE */
2919 'wl_user' => $id
2920 ), __METHOD__
2921 );
2922 # We also need to clear here the "you have new message" notification for the own user_talk page
2923 # This is cleared one page view later in Article::viewUpdates();
2924 }
2925 }
2926
2927 /**
2928 * Set this user's options from an encoded string
2929 * @param $str String Encoded options to import
2930 *
2931 * @deprecated in 1.19 due to removal of user_options from the user table
2932 */
2933 private function decodeOptions( $str ) {
2934 wfDeprecated( __METHOD__, '1.19' );
2935 if( !$str )
2936 return;
2937
2938 $this->mOptionsLoaded = true;
2939 $this->mOptionOverrides = array();
2940
2941 // If an option is not set in $str, use the default value
2942 $this->mOptions = self::getDefaultOptions();
2943
2944 $a = explode( "\n", $str );
2945 foreach ( $a as $s ) {
2946 $m = array();
2947 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2948 $this->mOptions[$m[1]] = $m[2];
2949 $this->mOptionOverrides[$m[1]] = $m[2];
2950 }
2951 }
2952 }
2953
2954 /**
2955 * Set a cookie on the user's client. Wrapper for
2956 * WebResponse::setCookie
2957 * @param $name String Name of the cookie to set
2958 * @param $value String Value to set
2959 * @param $exp Int Expiration time, as a UNIX time value;
2960 * if 0 or not specified, use the default $wgCookieExpiration
2961 * @param $secure Bool
2962 * true: Force setting the secure attribute when setting the cookie
2963 * false: Force NOT setting the secure attribute when setting the cookie
2964 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
2965 */
2966 protected function setCookie( $name, $value, $exp = 0, $secure = null ) {
2967 $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure );
2968 }
2969
2970 /**
2971 * Clear a cookie on the user's client
2972 * @param $name String Name of the cookie to clear
2973 */
2974 protected function clearCookie( $name ) {
2975 $this->setCookie( $name, '', time() - 86400 );
2976 }
2977
2978 /**
2979 * Set the default cookies for this session on the user's client.
2980 *
2981 * @param $request WebRequest object to use; $wgRequest will be used if null
2982 * is passed.
2983 * @param $secure bool Whether to force secure/insecure cookies or use default
2984 */
2985 public function setCookies( $request = null, $secure = null ) {
2986 if ( $request === null ) {
2987 $request = $this->getRequest();
2988 }
2989
2990 $this->load();
2991 if ( 0 == $this->mId ) {
2992 return;
2993 }
2994 if ( !$this->mToken ) {
2995 // When token is empty or NULL generate a new one and then save it to the database
2996 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
2997 // Simply by setting every cell in the user_token column to NULL and letting them be
2998 // regenerated as users log back into the wiki.
2999 $this->setToken();
3000 $this->saveSettings();
3001 }
3002 $session = array(
3003 'wsUserID' => $this->mId,
3004 'wsToken' => $this->mToken,
3005 'wsUserName' => $this->getName()
3006 );
3007 $cookies = array(
3008 'UserID' => $this->mId,
3009 'UserName' => $this->getName(),
3010 );
3011 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3012 $cookies['Token'] = $this->mToken;
3013 } else {
3014 $cookies['Token'] = false;
3015 }
3016
3017 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3018
3019 foreach ( $session as $name => $value ) {
3020 $request->setSessionData( $name, $value );
3021 }
3022 foreach ( $cookies as $name => $value ) {
3023 if ( $value === false ) {
3024 $this->clearCookie( $name );
3025 } else {
3026 $this->setCookie( $name, $value, 0, $secure );
3027 }
3028 }
3029
3030 /**
3031 * If wpStickHTTPS was selected, also set an insecure cookie that
3032 * will cause the site to redirect the user to HTTPS, if they access
3033 * it over HTTP. Bug 29898.
3034 */
3035 if ( $request->getCheck( 'wpStickHTTPS' ) ) {
3036 $this->setCookie( 'forceHTTPS', 'true', time() + 2592000, false ); //30 days
3037 }
3038 }
3039
3040 /**
3041 * Log this user out.
3042 */
3043 public function logout() {
3044 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3045 $this->doLogout();
3046 }
3047 }
3048
3049 /**
3050 * Clear the user's cookies and session, and reset the instance cache.
3051 * @see logout()
3052 */
3053 public function doLogout() {
3054 $this->clearInstanceCache( 'defaults' );
3055
3056 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3057
3058 $this->clearCookie( 'UserID' );
3059 $this->clearCookie( 'Token' );
3060 $this->clearCookie( 'forceHTTPS' );
3061
3062 # Remember when user logged out, to prevent seeing cached pages
3063 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
3064 }
3065
3066 /**
3067 * Save this user's settings into the database.
3068 * @todo Only rarely do all these fields need to be set!
3069 */
3070 public function saveSettings() {
3071 global $wgAuth;
3072
3073 $this->load();
3074 if ( wfReadOnly() ) { return; }
3075 if ( 0 == $this->mId ) { return; }
3076
3077 $this->mTouched = self::newTouchedTimestamp();
3078 if ( !$wgAuth->allowSetLocalPassword() ) {
3079 $this->mPassword = '';
3080 }
3081
3082 $dbw = wfGetDB( DB_MASTER );
3083 $dbw->update( 'user',
3084 array( /* SET */
3085 'user_name' => $this->mName,
3086 'user_password' => $this->mPassword,
3087 'user_newpassword' => $this->mNewpassword,
3088 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3089 'user_real_name' => $this->mRealName,
3090 'user_email' => $this->mEmail,
3091 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3092 'user_touched' => $dbw->timestamp( $this->mTouched ),
3093 'user_token' => strval( $this->mToken ),
3094 'user_email_token' => $this->mEmailToken,
3095 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3096 ), array( /* WHERE */
3097 'user_id' => $this->mId
3098 ), __METHOD__
3099 );
3100
3101 $this->saveOptions();
3102
3103 wfRunHooks( 'UserSaveSettings', array( $this ) );
3104 $this->clearSharedCache();
3105 $this->getUserPage()->invalidateCache();
3106 }
3107
3108 /**
3109 * If only this user's username is known, and it exists, return the user ID.
3110 * @return Int
3111 */
3112 public function idForName() {
3113 $s = trim( $this->getName() );
3114 if ( $s === '' ) return 0;
3115
3116 $dbr = wfGetDB( DB_SLAVE );
3117 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3118 if ( $id === false ) {
3119 $id = 0;
3120 }
3121 return $id;
3122 }
3123
3124 /**
3125 * Add a user to the database, return the user object
3126 *
3127 * @param $name String Username to add
3128 * @param $params Array of Strings Non-default parameters to save to the database as user_* fields:
3129 * - password The user's password hash. Password logins will be disabled if this is omitted.
3130 * - newpassword Hash for a temporary password that has been mailed to the user
3131 * - email The user's email address
3132 * - email_authenticated The email authentication timestamp
3133 * - real_name The user's real name
3134 * - options An associative array of non-default options
3135 * - token Random authentication token. Do not set.
3136 * - registration Registration timestamp. Do not set.
3137 *
3138 * @return User object, or null if the username already exists
3139 */
3140 public static function createNew( $name, $params = array() ) {
3141 $user = new User;
3142 $user->load();
3143 $user->setToken(); // init token
3144 if ( isset( $params['options'] ) ) {
3145 $user->mOptions = $params['options'] + (array)$user->mOptions;
3146 unset( $params['options'] );
3147 }
3148 $dbw = wfGetDB( DB_MASTER );
3149 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3150
3151 $fields = array(
3152 'user_id' => $seqVal,
3153 'user_name' => $name,
3154 'user_password' => $user->mPassword,
3155 'user_newpassword' => $user->mNewpassword,
3156 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3157 'user_email' => $user->mEmail,
3158 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3159 'user_real_name' => $user->mRealName,
3160 'user_token' => strval( $user->mToken ),
3161 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3162 'user_editcount' => 0,
3163 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3164 );
3165 foreach ( $params as $name => $value ) {
3166 $fields["user_$name"] = $value;
3167 }
3168 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3169 if ( $dbw->affectedRows() ) {
3170 $newUser = User::newFromId( $dbw->insertId() );
3171 } else {
3172 $newUser = null;
3173 }
3174 return $newUser;
3175 }
3176
3177 /**
3178 * Add this existing user object to the database. If the user already
3179 * exists, a fatal status object is returned, and the user object is
3180 * initialised with the data from the database.
3181 *
3182 * Previously, this function generated a DB error due to a key conflict
3183 * if the user already existed. Many extension callers use this function
3184 * in code along the lines of:
3185 *
3186 * $user = User::newFromName( $name );
3187 * if ( !$user->isLoggedIn() ) {
3188 * $user->addToDatabase();
3189 * }
3190 * // do something with $user...
3191 *
3192 * However, this was vulnerable to a race condition (bug 16020). By
3193 * initialising the user object if the user exists, we aim to support this
3194 * calling sequence as far as possible.
3195 *
3196 * Note that if the user exists, this function will acquire a write lock,
3197 * so it is still advisable to make the call conditional on isLoggedIn(),
3198 * and to commit the transaction after calling.
3199 *
3200 * @throws MWException
3201 * @return Status
3202 */
3203 public function addToDatabase() {
3204 $this->load();
3205 if ( !$this->mToken ) {
3206 $this->setToken(); // init token
3207 }
3208
3209 $this->mTouched = self::newTouchedTimestamp();
3210
3211 $dbw = wfGetDB( DB_MASTER );
3212 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3213 $dbw->insert( 'user',
3214 array(
3215 'user_id' => $seqVal,
3216 'user_name' => $this->mName,
3217 'user_password' => $this->mPassword,
3218 'user_newpassword' => $this->mNewpassword,
3219 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3220 'user_email' => $this->mEmail,
3221 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3222 'user_real_name' => $this->mRealName,
3223 'user_token' => strval( $this->mToken ),
3224 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3225 'user_editcount' => 0,
3226 'user_touched' => $dbw->timestamp( $this->mTouched ),
3227 ), __METHOD__,
3228 array( 'IGNORE' )
3229 );
3230 if ( !$dbw->affectedRows() ) {
3231 $this->mId = $dbw->selectField( 'user', 'user_id',
3232 array( 'user_name' => $this->mName ), __METHOD__ );
3233 $loaded = false;
3234 if ( $this->mId ) {
3235 if ( $this->loadFromDatabase() ) {
3236 $loaded = true;
3237 }
3238 }
3239 if ( !$loaded ) {
3240 throw new MWException( __METHOD__. ": hit a key conflict attempting " .
3241 "to insert a user row, but then it doesn't exist when we select it!" );
3242 }
3243 return Status::newFatal( 'userexists' );
3244 }
3245 $this->mId = $dbw->insertId();
3246
3247 // Clear instance cache other than user table data, which is already accurate
3248 $this->clearInstanceCache();
3249
3250 $this->saveOptions();
3251 return Status::newGood();
3252 }
3253
3254 /**
3255 * If this user is logged-in and blocked,
3256 * block any IP address they've successfully logged in from.
3257 * @return bool A block was spread
3258 */
3259 public function spreadAnyEditBlock() {
3260 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3261 return $this->spreadBlock();
3262 }
3263 return false;
3264 }
3265
3266 /**
3267 * If this (non-anonymous) user is blocked,
3268 * block the IP address they've successfully logged in from.
3269 * @return bool A block was spread
3270 */
3271 protected function spreadBlock() {
3272 wfDebug( __METHOD__ . "()\n" );
3273 $this->load();
3274 if ( $this->mId == 0 ) {
3275 return false;
3276 }
3277
3278 $userblock = Block::newFromTarget( $this->getName() );
3279 if ( !$userblock ) {
3280 return false;
3281 }
3282
3283 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3284 }
3285
3286 /**
3287 * Generate a string which will be different for any combination of
3288 * user options which would produce different parser output.
3289 * This will be used as part of the hash key for the parser cache,
3290 * so users with the same options can share the same cached data
3291 * safely.
3292 *
3293 * Extensions which require it should install 'PageRenderingHash' hook,
3294 * which will give them a chance to modify this key based on their own
3295 * settings.
3296 *
3297 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3298 * @return String Page rendering hash
3299 */
3300 public function getPageRenderingHash() {
3301 wfDeprecated( __METHOD__, '1.17' );
3302
3303 global $wgRenderHashAppend, $wgLang, $wgContLang;
3304 if( $this->mHash ) {
3305 return $this->mHash;
3306 }
3307
3308 // stubthreshold is only included below for completeness,
3309 // since it disables the parser cache, its value will always
3310 // be 0 when this function is called by parsercache.
3311
3312 $confstr = $this->getOption( 'math' );
3313 $confstr .= '!' . $this->getStubThreshold();
3314 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
3315 $confstr .= '!' . $wgLang->getCode();
3316 $confstr .= '!' . $this->getOption( 'thumbsize' );
3317 // add in language specific options, if any
3318 $extra = $wgContLang->getExtraHashOptions();
3319 $confstr .= $extra;
3320
3321 // Since the skin could be overloading link(), it should be
3322 // included here but in practice, none of our skins do that.
3323
3324 $confstr .= $wgRenderHashAppend;
3325
3326 // Give a chance for extensions to modify the hash, if they have
3327 // extra options or other effects on the parser cache.
3328 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3329
3330 // Make it a valid memcached key fragment
3331 $confstr = str_replace( ' ', '_', $confstr );
3332 $this->mHash = $confstr;
3333 return $confstr;
3334 }
3335
3336 /**
3337 * Get whether the user is explicitly blocked from account creation.
3338 * @return Bool|Block
3339 */
3340 public function isBlockedFromCreateAccount() {
3341 $this->getBlockedStatus();
3342 if( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3343 return $this->mBlock;
3344 }
3345
3346 # bug 13611: if the IP address the user is trying to create an account from is
3347 # blocked with createaccount disabled, prevent new account creation there even
3348 # when the user is logged in
3349 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3350 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3351 }
3352 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3353 ? $this->mBlockedFromCreateAccount
3354 : false;
3355 }
3356
3357 /**
3358 * Get whether the user is blocked from using Special:Emailuser.
3359 * @return Bool
3360 */
3361 public function isBlockedFromEmailuser() {
3362 $this->getBlockedStatus();
3363 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3364 }
3365
3366 /**
3367 * Get whether the user is allowed to create an account.
3368 * @return Bool
3369 */
3370 function isAllowedToCreateAccount() {
3371 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3372 }
3373
3374 /**
3375 * Get this user's personal page title.
3376 *
3377 * @return Title: User's personal page title
3378 */
3379 public function getUserPage() {
3380 return Title::makeTitle( NS_USER, $this->getName() );
3381 }
3382
3383 /**
3384 * Get this user's talk page title.
3385 *
3386 * @return Title: User's talk page title
3387 */
3388 public function getTalkPage() {
3389 $title = $this->getUserPage();
3390 return $title->getTalkPage();
3391 }
3392
3393 /**
3394 * Determine whether the user is a newbie. Newbies are either
3395 * anonymous IPs, or the most recently created accounts.
3396 * @return Bool
3397 */
3398 public function isNewbie() {
3399 return !$this->isAllowed( 'autoconfirmed' );
3400 }
3401
3402 /**
3403 * Check to see if the given clear-text password is one of the accepted passwords
3404 * @param $password String: user password.
3405 * @return Boolean: True if the given password is correct, otherwise False.
3406 */
3407 public function checkPassword( $password ) {
3408 global $wgAuth, $wgLegacyEncoding;
3409 $this->load();
3410
3411 // Even though we stop people from creating passwords that
3412 // are shorter than this, doesn't mean people wont be able
3413 // to. Certain authentication plugins do NOT want to save
3414 // domain passwords in a mysql database, so we should
3415 // check this (in case $wgAuth->strict() is false).
3416 if( !$this->isValidPassword( $password ) ) {
3417 return false;
3418 }
3419
3420 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
3421 return true;
3422 } elseif( $wgAuth->strict() ) {
3423 /* Auth plugin doesn't allow local authentication */
3424 return false;
3425 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
3426 /* Auth plugin doesn't allow local authentication for this user name */
3427 return false;
3428 }
3429 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3430 return true;
3431 } elseif ( $wgLegacyEncoding ) {
3432 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3433 # Check for this with iconv
3434 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3435 if ( $cp1252Password != $password &&
3436 self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
3437 {
3438 return true;
3439 }
3440 }
3441 return false;
3442 }
3443
3444 /**
3445 * Check if the given clear-text password matches the temporary password
3446 * sent by e-mail for password reset operations.
3447 *
3448 * @param $plaintext string
3449 *
3450 * @return Boolean: True if matches, false otherwise
3451 */
3452 public function checkTemporaryPassword( $plaintext ) {
3453 global $wgNewPasswordExpiry;
3454
3455 $this->load();
3456 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3457 if ( is_null( $this->mNewpassTime ) ) {
3458 return true;
3459 }
3460 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3461 return ( time() < $expiry );
3462 } else {
3463 return false;
3464 }
3465 }
3466
3467 /**
3468 * Alias for getEditToken.
3469 * @deprecated since 1.19, use getEditToken instead.
3470 *
3471 * @param $salt String|Array of Strings Optional function-specific data for hashing
3472 * @param $request WebRequest object to use or null to use $wgRequest
3473 * @return String The new edit token
3474 */
3475 public function editToken( $salt = '', $request = null ) {
3476 wfDeprecated( __METHOD__, '1.19' );
3477 return $this->getEditToken( $salt, $request );
3478 }
3479
3480 /**
3481 * Initialize (if necessary) and return a session token value
3482 * which can be used in edit forms to show that the user's
3483 * login credentials aren't being hijacked with a foreign form
3484 * submission.
3485 *
3486 * @since 1.19
3487 *
3488 * @param $salt String|Array of Strings Optional function-specific data for hashing
3489 * @param $request WebRequest object to use or null to use $wgRequest
3490 * @return String The new edit token
3491 */
3492 public function getEditToken( $salt = '', $request = null ) {
3493 if ( $request == null ) {
3494 $request = $this->getRequest();
3495 }
3496
3497 if ( $this->isAnon() ) {
3498 return EDIT_TOKEN_SUFFIX;
3499 } else {
3500 $token = $request->getSessionData( 'wsEditToken' );
3501 if ( $token === null ) {
3502 $token = MWCryptRand::generateHex( 32 );
3503 $request->setSessionData( 'wsEditToken', $token );
3504 }
3505 if( is_array( $salt ) ) {
3506 $salt = implode( '|', $salt );
3507 }
3508 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3509 }
3510 }
3511
3512 /**
3513 * Generate a looking random token for various uses.
3514 *
3515 * @return String The new random token
3516 * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pesudo-randomness
3517 */
3518 public static function generateToken() {
3519 return MWCryptRand::generateHex( 32 );
3520 }
3521
3522 /**
3523 * Check given value against the token value stored in the session.
3524 * A match should confirm that the form was submitted from the
3525 * user's own login session, not a form submission from a third-party
3526 * site.
3527 *
3528 * @param $val String Input value to compare
3529 * @param $salt String Optional function-specific data for hashing
3530 * @param $request WebRequest object to use or null to use $wgRequest
3531 * @return Boolean: Whether the token matches
3532 */
3533 public function matchEditToken( $val, $salt = '', $request = null ) {
3534 $sessionToken = $this->getEditToken( $salt, $request );
3535 if ( $val != $sessionToken ) {
3536 wfDebug( "User::matchEditToken: broken session data\n" );
3537 }
3538 return $val == $sessionToken;
3539 }
3540
3541 /**
3542 * Check given value against the token value stored in the session,
3543 * ignoring the suffix.
3544 *
3545 * @param $val String Input value to compare
3546 * @param $salt String Optional function-specific data for hashing
3547 * @param $request WebRequest object to use or null to use $wgRequest
3548 * @return Boolean: Whether the token matches
3549 */
3550 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3551 $sessionToken = $this->getEditToken( $salt, $request );
3552 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3553 }
3554
3555 /**
3556 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3557 * mail to the user's given address.
3558 *
3559 * @param $type String: message to send, either "created", "changed" or "set"
3560 * @return Status object
3561 */
3562 public function sendConfirmationMail( $type = 'created' ) {
3563 global $wgLang;
3564 $expiration = null; // gets passed-by-ref and defined in next line.
3565 $token = $this->confirmationToken( $expiration );
3566 $url = $this->confirmationTokenUrl( $token );
3567 $invalidateURL = $this->invalidationTokenUrl( $token );
3568 $this->saveSettings();
3569
3570 if ( $type == 'created' || $type === false ) {
3571 $message = 'confirmemail_body';
3572 } elseif ( $type === true ) {
3573 $message = 'confirmemail_body_changed';
3574 } else {
3575 $message = 'confirmemail_body_' . $type;
3576 }
3577
3578 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3579 wfMessage( $message,
3580 $this->getRequest()->getIP(),
3581 $this->getName(),
3582 $url,
3583 $wgLang->timeanddate( $expiration, false ),
3584 $invalidateURL,
3585 $wgLang->date( $expiration, false ),
3586 $wgLang->time( $expiration, false ) )->text() );
3587 }
3588
3589 /**
3590 * Send an e-mail to this user's account. Does not check for
3591 * confirmed status or validity.
3592 *
3593 * @param $subject String Message subject
3594 * @param $body String Message body
3595 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
3596 * @param $replyto String Reply-To address
3597 * @return Status
3598 */
3599 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3600 if( is_null( $from ) ) {
3601 global $wgPasswordSender, $wgPasswordSenderName;
3602 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3603 } else {
3604 $sender = new MailAddress( $from );
3605 }
3606
3607 $to = new MailAddress( $this );
3608 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3609 }
3610
3611 /**
3612 * Generate, store, and return a new e-mail confirmation code.
3613 * A hash (unsalted, since it's used as a key) is stored.
3614 *
3615 * @note Call saveSettings() after calling this function to commit
3616 * this change to the database.
3617 *
3618 * @param &$expiration \mixed Accepts the expiration time
3619 * @return String New token
3620 */
3621 private function confirmationToken( &$expiration ) {
3622 global $wgUserEmailConfirmationTokenExpiry;
3623 $now = time();
3624 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3625 $expiration = wfTimestamp( TS_MW, $expires );
3626 $this->load();
3627 $token = MWCryptRand::generateHex( 32 );
3628 $hash = md5( $token );
3629 $this->mEmailToken = $hash;
3630 $this->mEmailTokenExpires = $expiration;
3631 return $token;
3632 }
3633
3634 /**
3635 * Return a URL the user can use to confirm their email address.
3636 * @param $token String Accepts the email confirmation token
3637 * @return String New token URL
3638 */
3639 private function confirmationTokenUrl( $token ) {
3640 return $this->getTokenUrl( 'ConfirmEmail', $token );
3641 }
3642
3643 /**
3644 * Return a URL the user can use to invalidate their email address.
3645 * @param $token String Accepts the email confirmation token
3646 * @return String New token URL
3647 */
3648 private function invalidationTokenUrl( $token ) {
3649 return $this->getTokenUrl( 'InvalidateEmail', $token );
3650 }
3651
3652 /**
3653 * Internal function to format the e-mail validation/invalidation URLs.
3654 * This uses a quickie hack to use the
3655 * hardcoded English names of the Special: pages, for ASCII safety.
3656 *
3657 * @note Since these URLs get dropped directly into emails, using the
3658 * short English names avoids insanely long URL-encoded links, which
3659 * also sometimes can get corrupted in some browsers/mailers
3660 * (bug 6957 with Gmail and Internet Explorer).
3661 *
3662 * @param $page String Special page
3663 * @param $token String Token
3664 * @return String Formatted URL
3665 */
3666 protected function getTokenUrl( $page, $token ) {
3667 // Hack to bypass localization of 'Special:'
3668 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3669 return $title->getCanonicalUrl();
3670 }
3671
3672 /**
3673 * Mark the e-mail address confirmed.
3674 *
3675 * @note Call saveSettings() after calling this function to commit the change.
3676 *
3677 * @return bool
3678 */
3679 public function confirmEmail() {
3680 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3681 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3682 return true;
3683 }
3684
3685 /**
3686 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3687 * address if it was already confirmed.
3688 *
3689 * @note Call saveSettings() after calling this function to commit the change.
3690 * @return bool Returns true
3691 */
3692 function invalidateEmail() {
3693 $this->load();
3694 $this->mEmailToken = null;
3695 $this->mEmailTokenExpires = null;
3696 $this->setEmailAuthenticationTimestamp( null );
3697 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3698 return true;
3699 }
3700
3701 /**
3702 * Set the e-mail authentication timestamp.
3703 * @param $timestamp String TS_MW timestamp
3704 */
3705 function setEmailAuthenticationTimestamp( $timestamp ) {
3706 $this->load();
3707 $this->mEmailAuthenticated = $timestamp;
3708 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3709 }
3710
3711 /**
3712 * Is this user allowed to send e-mails within limits of current
3713 * site configuration?
3714 * @return Bool
3715 */
3716 public function canSendEmail() {
3717 global $wgEnableEmail, $wgEnableUserEmail;
3718 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3719 return false;
3720 }
3721 $canSend = $this->isEmailConfirmed();
3722 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3723 return $canSend;
3724 }
3725
3726 /**
3727 * Is this user allowed to receive e-mails within limits of current
3728 * site configuration?
3729 * @return Bool
3730 */
3731 public function canReceiveEmail() {
3732 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3733 }
3734
3735 /**
3736 * Is this user's e-mail address valid-looking and confirmed within
3737 * limits of the current site configuration?
3738 *
3739 * @note If $wgEmailAuthentication is on, this may require the user to have
3740 * confirmed their address by returning a code or using a password
3741 * sent to the address from the wiki.
3742 *
3743 * @return Bool
3744 */
3745 public function isEmailConfirmed() {
3746 global $wgEmailAuthentication;
3747 $this->load();
3748 $confirmed = true;
3749 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3750 if( $this->isAnon() ) {
3751 return false;
3752 }
3753 if( !Sanitizer::validateEmail( $this->mEmail ) ) {
3754 return false;
3755 }
3756 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3757 return false;
3758 }
3759 return true;
3760 } else {
3761 return $confirmed;
3762 }
3763 }
3764
3765 /**
3766 * Check whether there is an outstanding request for e-mail confirmation.
3767 * @return Bool
3768 */
3769 public function isEmailConfirmationPending() {
3770 global $wgEmailAuthentication;
3771 return $wgEmailAuthentication &&
3772 !$this->isEmailConfirmed() &&
3773 $this->mEmailToken &&
3774 $this->mEmailTokenExpires > wfTimestamp();
3775 }
3776
3777 /**
3778 * Get the timestamp of account creation.
3779 *
3780 * @return String|Bool|Null Timestamp of account creation, false for
3781 * non-existent/anonymous user accounts, or null if existing account
3782 * but information is not in database.
3783 */
3784 public function getRegistration() {
3785 if ( $this->isAnon() ) {
3786 return false;
3787 }
3788 $this->load();
3789 return $this->mRegistration;
3790 }
3791
3792 /**
3793 * Get the timestamp of the first edit
3794 *
3795 * @return String|Bool Timestamp of first edit, or false for
3796 * non-existent/anonymous user accounts.
3797 */
3798 public function getFirstEditTimestamp() {
3799 if( $this->getId() == 0 ) {
3800 return false; // anons
3801 }
3802 $dbr = wfGetDB( DB_SLAVE );
3803 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3804 array( 'rev_user' => $this->getId() ),
3805 __METHOD__,
3806 array( 'ORDER BY' => 'rev_timestamp ASC' )
3807 );
3808 if( !$time ) {
3809 return false; // no edits
3810 }
3811 return wfTimestamp( TS_MW, $time );
3812 }
3813
3814 /**
3815 * Get the permissions associated with a given list of groups
3816 *
3817 * @param $groups Array of Strings List of internal group names
3818 * @return Array of Strings List of permission key names for given groups combined
3819 */
3820 public static function getGroupPermissions( $groups ) {
3821 global $wgGroupPermissions, $wgRevokePermissions;
3822 $rights = array();
3823 // grant every granted permission first
3824 foreach( $groups as $group ) {
3825 if( isset( $wgGroupPermissions[$group] ) ) {
3826 $rights = array_merge( $rights,
3827 // array_filter removes empty items
3828 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3829 }
3830 }
3831 // now revoke the revoked permissions
3832 foreach( $groups as $group ) {
3833 if( isset( $wgRevokePermissions[$group] ) ) {
3834 $rights = array_diff( $rights,
3835 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3836 }
3837 }
3838 return array_unique( $rights );
3839 }
3840
3841 /**
3842 * Get all the groups who have a given permission
3843 *
3844 * @param $role String Role to check
3845 * @return Array of Strings List of internal group names with the given permission
3846 */
3847 public static function getGroupsWithPermission( $role ) {
3848 global $wgGroupPermissions;
3849 $allowedGroups = array();
3850 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
3851 if ( self::groupHasPermission( $group, $role ) ) {
3852 $allowedGroups[] = $group;
3853 }
3854 }
3855 return $allowedGroups;
3856 }
3857
3858 /**
3859 * Check, if the given group has the given permission
3860 *
3861 * @param $group String Group to check
3862 * @param $role String Role to check
3863 * @return bool
3864 */
3865 public static function groupHasPermission( $group, $role ) {
3866 global $wgGroupPermissions, $wgRevokePermissions;
3867 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
3868 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
3869 }
3870
3871 /**
3872 * Get the localized descriptive name for a group, if it exists
3873 *
3874 * @param $group String Internal group name
3875 * @return String Localized descriptive group name
3876 */
3877 public static function getGroupName( $group ) {
3878 $msg = wfMessage( "group-$group" );
3879 return $msg->isBlank() ? $group : $msg->text();
3880 }
3881
3882 /**
3883 * Get the localized descriptive name for a member of a group, if it exists
3884 *
3885 * @param $group String Internal group name
3886 * @param $username String Username for gender (since 1.19)
3887 * @return String Localized name for group member
3888 */
3889 public static function getGroupMember( $group, $username = '#' ) {
3890 $msg = wfMessage( "group-$group-member", $username );
3891 return $msg->isBlank() ? $group : $msg->text();
3892 }
3893
3894 /**
3895 * Return the set of defined explicit groups.
3896 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3897 * are not included, as they are defined automatically, not in the database.
3898 * @return Array of internal group names
3899 */
3900 public static function getAllGroups() {
3901 global $wgGroupPermissions, $wgRevokePermissions;
3902 return array_diff(
3903 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3904 self::getImplicitGroups()
3905 );
3906 }
3907
3908 /**
3909 * Get a list of all available permissions.
3910 * @return Array of permission names
3911 */
3912 public static function getAllRights() {
3913 if ( self::$mAllRights === false ) {
3914 global $wgAvailableRights;
3915 if ( count( $wgAvailableRights ) ) {
3916 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3917 } else {
3918 self::$mAllRights = self::$mCoreRights;
3919 }
3920 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3921 }
3922 return self::$mAllRights;
3923 }
3924
3925 /**
3926 * Get a list of implicit groups
3927 * @return Array of Strings Array of internal group names
3928 */
3929 public static function getImplicitGroups() {
3930 global $wgImplicitGroups;
3931 $groups = $wgImplicitGroups;
3932 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3933 return $groups;
3934 }
3935
3936 /**
3937 * Get the title of a page describing a particular group
3938 *
3939 * @param $group String Internal group name
3940 * @return Title|Bool Title of the page if it exists, false otherwise
3941 */
3942 public static function getGroupPage( $group ) {
3943 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3944 if( $msg->exists() ) {
3945 $title = Title::newFromText( $msg->text() );
3946 if( is_object( $title ) )
3947 return $title;
3948 }
3949 return false;
3950 }
3951
3952 /**
3953 * Create a link to the group in HTML, if available;
3954 * else return the group name.
3955 *
3956 * @param $group String Internal name of the group
3957 * @param $text String The text of the link
3958 * @return String HTML link to the group
3959 */
3960 public static function makeGroupLinkHTML( $group, $text = '' ) {
3961 if( $text == '' ) {
3962 $text = self::getGroupName( $group );
3963 }
3964 $title = self::getGroupPage( $group );
3965 if( $title ) {
3966 return Linker::link( $title, htmlspecialchars( $text ) );
3967 } else {
3968 return $text;
3969 }
3970 }
3971
3972 /**
3973 * Create a link to the group in Wikitext, if available;
3974 * else return the group name.
3975 *
3976 * @param $group String Internal name of the group
3977 * @param $text String The text of the link
3978 * @return String Wikilink to the group
3979 */
3980 public static function makeGroupLinkWiki( $group, $text = '' ) {
3981 if( $text == '' ) {
3982 $text = self::getGroupName( $group );
3983 }
3984 $title = self::getGroupPage( $group );
3985 if( $title ) {
3986 $page = $title->getPrefixedText();
3987 return "[[$page|$text]]";
3988 } else {
3989 return $text;
3990 }
3991 }
3992
3993 /**
3994 * Returns an array of the groups that a particular group can add/remove.
3995 *
3996 * @param $group String: the group to check for whether it can add/remove
3997 * @return Array array( 'add' => array( addablegroups ),
3998 * 'remove' => array( removablegroups ),
3999 * 'add-self' => array( addablegroups to self),
4000 * 'remove-self' => array( removable groups from self) )
4001 */
4002 public static function changeableByGroup( $group ) {
4003 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4004
4005 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4006 if( empty( $wgAddGroups[$group] ) ) {
4007 // Don't add anything to $groups
4008 } elseif( $wgAddGroups[$group] === true ) {
4009 // You get everything
4010 $groups['add'] = self::getAllGroups();
4011 } elseif( is_array( $wgAddGroups[$group] ) ) {
4012 $groups['add'] = $wgAddGroups[$group];
4013 }
4014
4015 // Same thing for remove
4016 if( empty( $wgRemoveGroups[$group] ) ) {
4017 } elseif( $wgRemoveGroups[$group] === true ) {
4018 $groups['remove'] = self::getAllGroups();
4019 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
4020 $groups['remove'] = $wgRemoveGroups[$group];
4021 }
4022
4023 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4024 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
4025 foreach( $wgGroupsAddToSelf as $key => $value ) {
4026 if( is_int( $key ) ) {
4027 $wgGroupsAddToSelf['user'][] = $value;
4028 }
4029 }
4030 }
4031
4032 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4033 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
4034 if( is_int( $key ) ) {
4035 $wgGroupsRemoveFromSelf['user'][] = $value;
4036 }
4037 }
4038 }
4039
4040 // Now figure out what groups the user can add to him/herself
4041 if( empty( $wgGroupsAddToSelf[$group] ) ) {
4042 } elseif( $wgGroupsAddToSelf[$group] === true ) {
4043 // No idea WHY this would be used, but it's there
4044 $groups['add-self'] = User::getAllGroups();
4045 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
4046 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4047 }
4048
4049 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4050 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
4051 $groups['remove-self'] = User::getAllGroups();
4052 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4053 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4054 }
4055
4056 return $groups;
4057 }
4058
4059 /**
4060 * Returns an array of groups that this user can add and remove
4061 * @return Array array( 'add' => array( addablegroups ),
4062 * 'remove' => array( removablegroups ),
4063 * 'add-self' => array( addablegroups to self),
4064 * 'remove-self' => array( removable groups from self) )
4065 */
4066 public function changeableGroups() {
4067 if( $this->isAllowed( 'userrights' ) ) {
4068 // This group gives the right to modify everything (reverse-
4069 // compatibility with old "userrights lets you change
4070 // everything")
4071 // Using array_merge to make the groups reindexed
4072 $all = array_merge( User::getAllGroups() );
4073 return array(
4074 'add' => $all,
4075 'remove' => $all,
4076 'add-self' => array(),
4077 'remove-self' => array()
4078 );
4079 }
4080
4081 // Okay, it's not so simple, we will have to go through the arrays
4082 $groups = array(
4083 'add' => array(),
4084 'remove' => array(),
4085 'add-self' => array(),
4086 'remove-self' => array()
4087 );
4088 $addergroups = $this->getEffectiveGroups();
4089
4090 foreach( $addergroups as $addergroup ) {
4091 $groups = array_merge_recursive(
4092 $groups, $this->changeableByGroup( $addergroup )
4093 );
4094 $groups['add'] = array_unique( $groups['add'] );
4095 $groups['remove'] = array_unique( $groups['remove'] );
4096 $groups['add-self'] = array_unique( $groups['add-self'] );
4097 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4098 }
4099 return $groups;
4100 }
4101
4102 /**
4103 * Increment the user's edit-count field.
4104 * Will have no effect for anonymous users.
4105 */
4106 public function incEditCount() {
4107 if( !$this->isAnon() ) {
4108 $dbw = wfGetDB( DB_MASTER );
4109 $dbw->update(
4110 'user',
4111 array( 'user_editcount=user_editcount+1' ),
4112 array( 'user_id' => $this->getId() ),
4113 __METHOD__
4114 );
4115
4116 // Lazy initialization check...
4117 if( $dbw->affectedRows() == 0 ) {
4118 // Now here's a goddamn hack...
4119 $dbr = wfGetDB( DB_SLAVE );
4120 if( $dbr !== $dbw ) {
4121 // If we actually have a slave server, the count is
4122 // at least one behind because the current transaction
4123 // has not been committed and replicated.
4124 $this->initEditCount( 1 );
4125 } else {
4126 // But if DB_SLAVE is selecting the master, then the
4127 // count we just read includes the revision that was
4128 // just added in the working transaction.
4129 $this->initEditCount();
4130 }
4131 }
4132 }
4133 // edit count in user cache too
4134 $this->invalidateCache();
4135 }
4136
4137 /**
4138 * Initialize user_editcount from data out of the revision table
4139 *
4140 * @param $add Integer Edits to add to the count from the revision table
4141 * @return Integer Number of edits
4142 */
4143 protected function initEditCount( $add = 0 ) {
4144 // Pull from a slave to be less cruel to servers
4145 // Accuracy isn't the point anyway here
4146 $dbr = wfGetDB( DB_SLAVE );
4147 $count = (int) $dbr->selectField(
4148 'revision',
4149 'COUNT(rev_user)',
4150 array( 'rev_user' => $this->getId() ),
4151 __METHOD__
4152 );
4153 $count = $count + $add;
4154
4155 $dbw = wfGetDB( DB_MASTER );
4156 $dbw->update(
4157 'user',
4158 array( 'user_editcount' => $count ),
4159 array( 'user_id' => $this->getId() ),
4160 __METHOD__
4161 );
4162
4163 return $count;
4164 }
4165
4166 /**
4167 * Get the description of a given right
4168 *
4169 * @param $right String Right to query
4170 * @return String Localized description of the right
4171 */
4172 public static function getRightDescription( $right ) {
4173 $key = "right-$right";
4174 $msg = wfMessage( $key );
4175 return $msg->isBlank() ? $right : $msg->text();
4176 }
4177
4178 /**
4179 * Make an old-style password hash
4180 *
4181 * @param $password String Plain-text password
4182 * @param $userId String User ID
4183 * @return String Password hash
4184 */
4185 public static function oldCrypt( $password, $userId ) {
4186 global $wgPasswordSalt;
4187 if ( $wgPasswordSalt ) {
4188 return md5( $userId . '-' . md5( $password ) );
4189 } else {
4190 return md5( $password );
4191 }
4192 }
4193
4194 /**
4195 * Make a new-style password hash
4196 *
4197 * @param $password String Plain-text password
4198 * @param bool|string $salt Optional salt, may be random or the user ID.
4199
4200 * If unspecified or false, will generate one automatically
4201 * @return String Password hash
4202 */
4203 public static function crypt( $password, $salt = false ) {
4204 global $wgPasswordSalt;
4205
4206 $hash = '';
4207 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4208 return $hash;
4209 }
4210
4211 if( $wgPasswordSalt ) {
4212 if ( $salt === false ) {
4213 $salt = MWCryptRand::generateHex( 8 );
4214 }
4215 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4216 } else {
4217 return ':A:' . md5( $password );
4218 }
4219 }
4220
4221 /**
4222 * Compare a password hash with a plain-text password. Requires the user
4223 * ID if there's a chance that the hash is an old-style hash.
4224 *
4225 * @param $hash String Password hash
4226 * @param $password String Plain-text password to compare
4227 * @param $userId String|bool User ID for old-style password salt
4228 *
4229 * @return Boolean
4230 */
4231 public static function comparePasswords( $hash, $password, $userId = false ) {
4232 $type = substr( $hash, 0, 3 );
4233
4234 $result = false;
4235 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4236 return $result;
4237 }
4238
4239 if ( $type == ':A:' ) {
4240 # Unsalted
4241 return md5( $password ) === substr( $hash, 3 );
4242 } elseif ( $type == ':B:' ) {
4243 # Salted
4244 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4245 return md5( $salt.'-'.md5( $password ) ) === $realHash;
4246 } else {
4247 # Old-style
4248 return self::oldCrypt( $password, $userId ) === $hash;
4249 }
4250 }
4251
4252 /**
4253 * Add a newuser log entry for this user.
4254 * Before 1.19 the return value was always true.
4255 *
4256 * @param $action string|bool: account creation type.
4257 * - String, one of the following values:
4258 * - 'create' for an anonymous user creating an account for himself.
4259 * This will force the action's performer to be the created user itself,
4260 * no matter the value of $wgUser
4261 * - 'create2' for a logged in user creating an account for someone else
4262 * - 'byemail' when the created user will receive its password by e-mail
4263 * - Boolean means whether the account was created by e-mail (deprecated):
4264 * - true will be converted to 'byemail'
4265 * - false will be converted to 'create' if this object is the same as
4266 * $wgUser and to 'create2' otherwise
4267 *
4268 * @param $reason String: user supplied reason
4269 *
4270 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4271 */
4272 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4273 global $wgUser, $wgNewUserLog;
4274 if( empty( $wgNewUserLog ) ) {
4275 return true; // disabled
4276 }
4277
4278 if ( $action === true ) {
4279 $action = 'byemail';
4280 } elseif ( $action === false ) {
4281 if ( $this->getName() == $wgUser->getName() ) {
4282 $action = 'create';
4283 } else {
4284 $action = 'create2';
4285 }
4286 }
4287
4288 if ( $action === 'create' || $action === 'autocreate' ) {
4289 $performer = $this;
4290 } else {
4291 $performer = $wgUser;
4292 }
4293
4294 $logEntry = new ManualLogEntry( 'newusers', $action );
4295 $logEntry->setPerformer( $performer );
4296 $logEntry->setTarget( $this->getUserPage() );
4297 $logEntry->setComment( $reason );
4298 $logEntry->setParameters( array(
4299 '4::userid' => $this->getId(),
4300 ) );
4301 $logid = $logEntry->insert();
4302
4303 if ( $action !== 'autocreate' ) {
4304 $logEntry->publish( $logid );
4305 }
4306
4307 return (int)$logid;
4308 }
4309
4310 /**
4311 * Add an autocreate newuser log entry for this user
4312 * Used by things like CentralAuth and perhaps other authplugins.
4313 * Consider calling addNewUserLogEntry() directly instead.
4314 *
4315 * @return bool
4316 */
4317 public function addNewUserLogEntryAutoCreate() {
4318 $this->addNewUserLogEntry( 'autocreate' );
4319
4320 return true;
4321 }
4322
4323 /**
4324 * Load the user options either from cache, the database or an array
4325 *
4326 * @param $data array Rows for the current user out of the user_properties table
4327 */
4328 protected function loadOptions( $data = null ) {
4329 global $wgContLang;
4330
4331 $this->load();
4332
4333 if ( $this->mOptionsLoaded ) {
4334 return;
4335 }
4336
4337 $this->mOptions = self::getDefaultOptions();
4338
4339 if ( !$this->getId() ) {
4340 // For unlogged-in users, load language/variant options from request.
4341 // There's no need to do it for logged-in users: they can set preferences,
4342 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4343 // so don't override user's choice (especially when the user chooses site default).
4344 $variant = $wgContLang->getDefaultVariant();
4345 $this->mOptions['variant'] = $variant;
4346 $this->mOptions['language'] = $variant;
4347 $this->mOptionsLoaded = true;
4348 return;
4349 }
4350
4351 // Maybe load from the object
4352 if ( !is_null( $this->mOptionOverrides ) ) {
4353 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4354 foreach( $this->mOptionOverrides as $key => $value ) {
4355 $this->mOptions[$key] = $value;
4356 }
4357 } else {
4358 if( !is_array( $data ) ) {
4359 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4360 // Load from database
4361 $dbr = wfGetDB( DB_SLAVE );
4362
4363 $res = $dbr->select(
4364 'user_properties',
4365 array( 'up_property', 'up_value' ),
4366 array( 'up_user' => $this->getId() ),
4367 __METHOD__
4368 );
4369
4370 $this->mOptionOverrides = array();
4371 $data = array();
4372 foreach ( $res as $row ) {
4373 $data[$row->up_property] = $row->up_value;
4374 }
4375 }
4376 foreach ( $data as $property => $value ) {
4377 $this->mOptionOverrides[$property] = $value;
4378 $this->mOptions[$property] = $value;
4379 }
4380 }
4381
4382 $this->mOptionsLoaded = true;
4383
4384 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4385 }
4386
4387 /**
4388 * @todo document
4389 */
4390 protected function saveOptions() {
4391 global $wgAllowPrefChange;
4392
4393 $this->loadOptions();
4394
4395 // Not using getOptions(), to keep hidden preferences in database
4396 $saveOptions = $this->mOptions;
4397
4398 // Allow hooks to abort, for instance to save to a global profile.
4399 // Reset options to default state before saving.
4400 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4401 return;
4402 }
4403
4404 $extuser = ExternalUser::newFromUser( $this );
4405 $userId = $this->getId();
4406 $insert_rows = array();
4407 foreach( $saveOptions as $key => $value ) {
4408 # Don't bother storing default values
4409 $defaultOption = self::getDefaultOption( $key );
4410 if ( ( is_null( $defaultOption ) &&
4411 !( $value === false || is_null( $value ) ) ) ||
4412 $value != $defaultOption ) {
4413 $insert_rows[] = array(
4414 'up_user' => $userId,
4415 'up_property' => $key,
4416 'up_value' => $value,
4417 );
4418 }
4419 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
4420 switch ( $wgAllowPrefChange[$key] ) {
4421 case 'local':
4422 case 'message':
4423 break;
4424 case 'semiglobal':
4425 case 'global':
4426 $extuser->setPref( $key, $value );
4427 }
4428 }
4429 }
4430
4431 $dbw = wfGetDB( DB_MASTER );
4432 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
4433 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
4434 }
4435
4436 /**
4437 * Provide an array of HTML5 attributes to put on an input element
4438 * intended for the user to enter a new password. This may include
4439 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4440 *
4441 * Do *not* use this when asking the user to enter his current password!
4442 * Regardless of configuration, users may have invalid passwords for whatever
4443 * reason (e.g., they were set before requirements were tightened up).
4444 * Only use it when asking for a new password, like on account creation or
4445 * ResetPass.
4446 *
4447 * Obviously, you still need to do server-side checking.
4448 *
4449 * NOTE: A combination of bugs in various browsers means that this function
4450 * actually just returns array() unconditionally at the moment. May as
4451 * well keep it around for when the browser bugs get fixed, though.
4452 *
4453 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4454 *
4455 * @return array Array of HTML attributes suitable for feeding to
4456 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4457 * That will potentially output invalid XHTML 1.0 Transitional, and will
4458 * get confused by the boolean attribute syntax used.)
4459 */
4460 public static function passwordChangeInputAttribs() {
4461 global $wgMinimalPasswordLength;
4462
4463 if ( $wgMinimalPasswordLength == 0 ) {
4464 return array();
4465 }
4466
4467 # Note that the pattern requirement will always be satisfied if the
4468 # input is empty, so we need required in all cases.
4469 #
4470 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4471 # if e-mail confirmation is being used. Since HTML5 input validation
4472 # is b0rked anyway in some browsers, just return nothing. When it's
4473 # re-enabled, fix this code to not output required for e-mail
4474 # registration.
4475 #$ret = array( 'required' );
4476 $ret = array();
4477
4478 # We can't actually do this right now, because Opera 9.6 will print out
4479 # the entered password visibly in its error message! When other
4480 # browsers add support for this attribute, or Opera fixes its support,
4481 # we can add support with a version check to avoid doing this on Opera
4482 # versions where it will be a problem. Reported to Opera as
4483 # DSK-262266, but they don't have a public bug tracker for us to follow.
4484 /*
4485 if ( $wgMinimalPasswordLength > 1 ) {
4486 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4487 $ret['title'] = wfMessage( 'passwordtooshort' )
4488 ->numParams( $wgMinimalPasswordLength )->text();
4489 }
4490 */
4491
4492 return $ret;
4493 }
4494
4495 /**
4496 * Return the list of user fields that should be selected to create
4497 * a new user object.
4498 * @return array
4499 */
4500 public static function selectFields() {
4501 return array(
4502 'user_id',
4503 'user_name',
4504 'user_real_name',
4505 'user_password',
4506 'user_newpassword',
4507 'user_newpass_time',
4508 'user_email',
4509 'user_touched',
4510 'user_token',
4511 'user_email_authenticated',
4512 'user_email_token',
4513 'user_email_token_expires',
4514 'user_registration',
4515 'user_editcount',
4516 );
4517 }
4518 }