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