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