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