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