Merge "resourceloader: Only store sources' load.php urls"
[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 StubObject::unstub( $wgAuth );
1889 $authUser = $wgAuth->getUserInstance( $this );
1890 $this->mLocked = (bool)$authUser->isLocked();
1891 return $this->mLocked;
1892 }
1893
1894 /**
1895 * Check if user account is hidden
1896 *
1897 * @return bool True if hidden, false otherwise
1898 */
1899 public function isHidden() {
1900 if ( $this->mHideName !== null ) {
1901 return $this->mHideName;
1902 }
1903 $this->getBlockedStatus();
1904 if ( !$this->mHideName ) {
1905 global $wgAuth;
1906 StubObject::unstub( $wgAuth );
1907 $authUser = $wgAuth->getUserInstance( $this );
1908 $this->mHideName = (bool)$authUser->isHidden();
1909 }
1910 return $this->mHideName;
1911 }
1912
1913 /**
1914 * Get the user's ID.
1915 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1916 */
1917 public function getId() {
1918 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1919 // Special case, we know the user is anonymous
1920 return 0;
1921 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1922 // Don't load if this was initialized from an ID
1923 $this->load();
1924 }
1925 return $this->mId;
1926 }
1927
1928 /**
1929 * Set the user and reload all fields according to a given ID
1930 * @param int $v User ID to reload
1931 */
1932 public function setId( $v ) {
1933 $this->mId = $v;
1934 $this->clearInstanceCache( 'id' );
1935 }
1936
1937 /**
1938 * Get the user name, or the IP of an anonymous user
1939 * @return string User's name or IP address
1940 */
1941 public function getName() {
1942 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1943 // Special case optimisation
1944 return $this->mName;
1945 } else {
1946 $this->load();
1947 if ( $this->mName === false ) {
1948 // Clean up IPs
1949 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1950 }
1951 return $this->mName;
1952 }
1953 }
1954
1955 /**
1956 * Set the user name.
1957 *
1958 * This does not reload fields from the database according to the given
1959 * name. Rather, it is used to create a temporary "nonexistent user" for
1960 * later addition to the database. It can also be used to set the IP
1961 * address for an anonymous user to something other than the current
1962 * remote IP.
1963 *
1964 * @note User::newFromName() has roughly the same function, when the named user
1965 * does not exist.
1966 * @param string $str New user name to set
1967 */
1968 public function setName( $str ) {
1969 $this->load();
1970 $this->mName = $str;
1971 }
1972
1973 /**
1974 * Get the user's name escaped by underscores.
1975 * @return string Username escaped by underscores.
1976 */
1977 public function getTitleKey() {
1978 return str_replace( ' ', '_', $this->getName() );
1979 }
1980
1981 /**
1982 * Check if the user has new messages.
1983 * @return bool True if the user has new messages
1984 */
1985 public function getNewtalk() {
1986 $this->load();
1987
1988 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1989 if ( $this->mNewtalk === -1 ) {
1990 $this->mNewtalk = false; # reset talk page status
1991
1992 // Check memcached separately for anons, who have no
1993 // entire User object stored in there.
1994 if ( !$this->mId ) {
1995 global $wgDisableAnonTalk;
1996 if ( $wgDisableAnonTalk ) {
1997 // Anon newtalk disabled by configuration.
1998 $this->mNewtalk = false;
1999 } else {
2000 global $wgMemc;
2001 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2002 $newtalk = $wgMemc->get( $key );
2003 if ( strval( $newtalk ) !== '' ) {
2004 $this->mNewtalk = (bool)$newtalk;
2005 } else {
2006 // Since we are caching this, make sure it is up to date by getting it
2007 // from the master
2008 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
2009 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
2010 }
2011 }
2012 } else {
2013 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2014 }
2015 }
2016
2017 return (bool)$this->mNewtalk;
2018 }
2019
2020 /**
2021 * Return the data needed to construct links for new talk page message
2022 * alerts. If there are new messages, this will return an associative array
2023 * with the following data:
2024 * wiki: The database name of the wiki
2025 * link: Root-relative link to the user's talk page
2026 * rev: The last talk page revision that the user has seen or null. This
2027 * is useful for building diff links.
2028 * If there are no new messages, it returns an empty array.
2029 * @note This function was designed to accomodate multiple talk pages, but
2030 * currently only returns a single link and revision.
2031 * @return array
2032 */
2033 public function getNewMessageLinks() {
2034 $talks = array();
2035 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2036 return $talks;
2037 } elseif ( !$this->getNewtalk() ) {
2038 return array();
2039 }
2040 $utp = $this->getTalkPage();
2041 $dbr = wfGetDB( DB_SLAVE );
2042 // Get the "last viewed rev" timestamp from the oldest message notification
2043 $timestamp = $dbr->selectField( 'user_newtalk',
2044 'MIN(user_last_timestamp)',
2045 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2046 __METHOD__ );
2047 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2048 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2049 }
2050
2051 /**
2052 * Get the revision ID for the last talk page revision viewed by the talk
2053 * page owner.
2054 * @return int|null Revision ID or null
2055 */
2056 public function getNewMessageRevisionId() {
2057 $newMessageRevisionId = null;
2058 $newMessageLinks = $this->getNewMessageLinks();
2059 if ( $newMessageLinks ) {
2060 // Note: getNewMessageLinks() never returns more than a single link
2061 // and it is always for the same wiki, but we double-check here in
2062 // case that changes some time in the future.
2063 if ( count( $newMessageLinks ) === 1
2064 && $newMessageLinks[0]['wiki'] === wfWikiID()
2065 && $newMessageLinks[0]['rev']
2066 ) {
2067 $newMessageRevision = $newMessageLinks[0]['rev'];
2068 $newMessageRevisionId = $newMessageRevision->getId();
2069 }
2070 }
2071 return $newMessageRevisionId;
2072 }
2073
2074 /**
2075 * Internal uncached check for new messages
2076 *
2077 * @see getNewtalk()
2078 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2079 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2080 * @param bool $fromMaster True to fetch from the master, false for a slave
2081 * @return bool True if the user has new messages
2082 */
2083 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2084 if ( $fromMaster ) {
2085 $db = wfGetDB( DB_MASTER );
2086 } else {
2087 $db = wfGetDB( DB_SLAVE );
2088 }
2089 $ok = $db->selectField( 'user_newtalk', $field,
2090 array( $field => $id ), __METHOD__ );
2091 return $ok !== false;
2092 }
2093
2094 /**
2095 * Add or update the new messages flag
2096 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2097 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2098 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2099 * @return bool True if successful, false otherwise
2100 */
2101 protected function updateNewtalk( $field, $id, $curRev = null ) {
2102 // Get timestamp of the talk page revision prior to the current one
2103 $prevRev = $curRev ? $curRev->getPrevious() : false;
2104 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2105 // Mark the user as having new messages since this revision
2106 $dbw = wfGetDB( DB_MASTER );
2107 $dbw->insert( 'user_newtalk',
2108 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2109 __METHOD__,
2110 'IGNORE' );
2111 if ( $dbw->affectedRows() ) {
2112 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2113 return true;
2114 } else {
2115 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2116 return false;
2117 }
2118 }
2119
2120 /**
2121 * Clear the new messages flag for the given user
2122 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2123 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2124 * @return bool True if successful, false otherwise
2125 */
2126 protected function deleteNewtalk( $field, $id ) {
2127 $dbw = wfGetDB( DB_MASTER );
2128 $dbw->delete( 'user_newtalk',
2129 array( $field => $id ),
2130 __METHOD__ );
2131 if ( $dbw->affectedRows() ) {
2132 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2133 return true;
2134 } else {
2135 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2136 return false;
2137 }
2138 }
2139
2140 /**
2141 * Update the 'You have new messages!' status.
2142 * @param bool $val Whether the user has new messages
2143 * @param Revision $curRev New, as yet unseen revision of the user talk
2144 * page. Ignored if null or !$val.
2145 */
2146 public function setNewtalk( $val, $curRev = null ) {
2147 if ( wfReadOnly() ) {
2148 return;
2149 }
2150
2151 $this->load();
2152 $this->mNewtalk = $val;
2153
2154 if ( $this->isAnon() ) {
2155 $field = 'user_ip';
2156 $id = $this->getName();
2157 } else {
2158 $field = 'user_id';
2159 $id = $this->getId();
2160 }
2161 global $wgMemc;
2162
2163 if ( $val ) {
2164 $changed = $this->updateNewtalk( $field, $id, $curRev );
2165 } else {
2166 $changed = $this->deleteNewtalk( $field, $id );
2167 }
2168
2169 if ( $this->isAnon() ) {
2170 // Anons have a separate memcached space, since
2171 // user records aren't kept for them.
2172 $key = wfMemcKey( 'newtalk', 'ip', $id );
2173 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2174 }
2175 if ( $changed ) {
2176 $this->invalidateCache();
2177 }
2178 }
2179
2180 /**
2181 * Generate a current or new-future timestamp to be stored in the
2182 * user_touched field when we update things.
2183 * @return string Timestamp in TS_MW format
2184 */
2185 private static function newTouchedTimestamp() {
2186 global $wgClockSkewFudge;
2187 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2188 }
2189
2190 /**
2191 * Clear user data from memcached.
2192 * Use after applying fun updates to the database; caller's
2193 * responsibility to update user_touched if appropriate.
2194 *
2195 * Called implicitly from invalidateCache() and saveSettings().
2196 */
2197 public function clearSharedCache() {
2198 $this->load();
2199 if ( $this->mId ) {
2200 global $wgMemc;
2201 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2202 }
2203 }
2204
2205 /**
2206 * Immediately touch the user data cache for this account.
2207 * Updates user_touched field, and removes account data from memcached
2208 * for reload on the next hit.
2209 */
2210 public function invalidateCache() {
2211 if ( wfReadOnly() ) {
2212 return;
2213 }
2214 $this->load();
2215 if ( $this->mId ) {
2216 $this->mTouched = self::newTouchedTimestamp();
2217
2218 $dbw = wfGetDB( DB_MASTER );
2219 $userid = $this->mId;
2220 $touched = $this->mTouched;
2221 $method = __METHOD__;
2222 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2223 // Prevent contention slams by checking user_touched first
2224 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2225 $needsPurge = $dbw->selectField( 'user', '1',
2226 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2227 if ( $needsPurge ) {
2228 $dbw->update( 'user',
2229 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2230 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2231 $method
2232 );
2233 }
2234 } );
2235 $this->clearSharedCache();
2236 }
2237 }
2238
2239 /**
2240 * Validate the cache for this account.
2241 * @param string $timestamp A timestamp in TS_MW format
2242 * @return bool
2243 */
2244 public function validateCache( $timestamp ) {
2245 $this->load();
2246 return ( $timestamp >= $this->mTouched );
2247 }
2248
2249 /**
2250 * Get the user touched timestamp
2251 * @return string Timestamp
2252 */
2253 public function getTouched() {
2254 $this->load();
2255 return $this->mTouched;
2256 }
2257
2258 /**
2259 * @return Password
2260 * @since 1.24
2261 */
2262 public function getPassword() {
2263 $this->loadPasswords();
2264
2265 return $this->mPassword;
2266 }
2267
2268 /**
2269 * @return Password
2270 * @since 1.24
2271 */
2272 public function getTemporaryPassword() {
2273 $this->loadPasswords();
2274
2275 return $this->mNewpassword;
2276 }
2277
2278 /**
2279 * Set the password and reset the random token.
2280 * Calls through to authentication plugin if necessary;
2281 * will have no effect if the auth plugin refuses to
2282 * pass the change through or if the legal password
2283 * checks fail.
2284 *
2285 * As a special case, setting the password to null
2286 * wipes it, so the account cannot be logged in until
2287 * a new password is set, for instance via e-mail.
2288 *
2289 * @param string $str New password to set
2290 * @throws PasswordError On failure
2291 *
2292 * @return bool
2293 */
2294 public function setPassword( $str ) {
2295 global $wgAuth;
2296
2297 $this->loadPasswords();
2298
2299 if ( $str !== null ) {
2300 if ( !$wgAuth->allowPasswordChange() ) {
2301 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2302 }
2303
2304 if ( !$this->isValidPassword( $str ) ) {
2305 global $wgMinimalPasswordLength;
2306 $valid = $this->getPasswordValidity( $str );
2307 if ( is_array( $valid ) ) {
2308 $message = array_shift( $valid );
2309 $params = $valid;
2310 } else {
2311 $message = $valid;
2312 $params = array( $wgMinimalPasswordLength );
2313 }
2314 throw new PasswordError( wfMessage( $message, $params )->text() );
2315 }
2316 }
2317
2318 if ( !$wgAuth->setPassword( $this, $str ) ) {
2319 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2320 }
2321
2322 $this->setInternalPassword( $str );
2323
2324 return true;
2325 }
2326
2327 /**
2328 * Set the password and reset the random token unconditionally.
2329 *
2330 * @param string|null $str New password to set or null to set an invalid
2331 * password hash meaning that the user will not be able to log in
2332 * through the web interface.
2333 */
2334 public function setInternalPassword( $str ) {
2335 $this->setToken();
2336
2337 $passwordFactory = self::getPasswordFactory();
2338 if ( $str === null ) {
2339 $this->mPassword = $passwordFactory->newFromCiphertext( null );
2340 } else {
2341 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2342 }
2343
2344 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2345 $this->mNewpassTime = null;
2346 }
2347
2348 /**
2349 * Get the user's current token.
2350 * @param bool $forceCreation Force the generation of a new token if the
2351 * user doesn't have one (default=true for backwards compatibility).
2352 * @return string Token
2353 */
2354 public function getToken( $forceCreation = true ) {
2355 $this->load();
2356 if ( !$this->mToken && $forceCreation ) {
2357 $this->setToken();
2358 }
2359 return $this->mToken;
2360 }
2361
2362 /**
2363 * Set the random token (used for persistent authentication)
2364 * Called from loadDefaults() among other places.
2365 *
2366 * @param string|bool $token If specified, set the token to this value
2367 */
2368 public function setToken( $token = false ) {
2369 $this->load();
2370 if ( !$token ) {
2371 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2372 } else {
2373 $this->mToken = $token;
2374 }
2375 }
2376
2377 /**
2378 * Set the password for a password reminder or new account email
2379 *
2380 * @param string $str New password to set or null to set an invalid
2381 * password hash meaning that the user will not be able to use it
2382 * @param bool $throttle If true, reset the throttle timestamp to the present
2383 */
2384 public function setNewpassword( $str, $throttle = true ) {
2385 $this->loadPasswords();
2386
2387 if ( $str === null ) {
2388 $this->mNewpassword = '';
2389 $this->mNewpassTime = null;
2390 } else {
2391 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2392 if ( $throttle ) {
2393 $this->mNewpassTime = wfTimestampNow();
2394 }
2395 }
2396 }
2397
2398 /**
2399 * Has password reminder email been sent within the last
2400 * $wgPasswordReminderResendTime hours?
2401 * @return bool
2402 */
2403 public function isPasswordReminderThrottled() {
2404 global $wgPasswordReminderResendTime;
2405 $this->load();
2406 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2407 return false;
2408 }
2409 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2410 return time() < $expiry;
2411 }
2412
2413 /**
2414 * Get the user's e-mail address
2415 * @return string User's email address
2416 */
2417 public function getEmail() {
2418 $this->load();
2419 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2420 return $this->mEmail;
2421 }
2422
2423 /**
2424 * Get the timestamp of the user's e-mail authentication
2425 * @return string TS_MW timestamp
2426 */
2427 public function getEmailAuthenticationTimestamp() {
2428 $this->load();
2429 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2430 return $this->mEmailAuthenticated;
2431 }
2432
2433 /**
2434 * Set the user's e-mail address
2435 * @param string $str New e-mail address
2436 */
2437 public function setEmail( $str ) {
2438 $this->load();
2439 if ( $str == $this->mEmail ) {
2440 return;
2441 }
2442 $this->invalidateEmail();
2443 $this->mEmail = $str;
2444 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2445 }
2446
2447 /**
2448 * Set the user's e-mail address and a confirmation mail if needed.
2449 *
2450 * @since 1.20
2451 * @param string $str New e-mail address
2452 * @return Status
2453 */
2454 public function setEmailWithConfirmation( $str ) {
2455 global $wgEnableEmail, $wgEmailAuthentication;
2456
2457 if ( !$wgEnableEmail ) {
2458 return Status::newFatal( 'emaildisabled' );
2459 }
2460
2461 $oldaddr = $this->getEmail();
2462 if ( $str === $oldaddr ) {
2463 return Status::newGood( true );
2464 }
2465
2466 $this->setEmail( $str );
2467
2468 if ( $str !== '' && $wgEmailAuthentication ) {
2469 // Send a confirmation request to the new address if needed
2470 $type = $oldaddr != '' ? 'changed' : 'set';
2471 $result = $this->sendConfirmationMail( $type );
2472 if ( $result->isGood() ) {
2473 // Say the the caller that a confirmation mail has been sent
2474 $result->value = 'eauth';
2475 }
2476 } else {
2477 $result = Status::newGood( true );
2478 }
2479
2480 return $result;
2481 }
2482
2483 /**
2484 * Get the user's real name
2485 * @return string User's real name
2486 */
2487 public function getRealName() {
2488 if ( !$this->isItemLoaded( 'realname' ) ) {
2489 $this->load();
2490 }
2491
2492 return $this->mRealName;
2493 }
2494
2495 /**
2496 * Set the user's real name
2497 * @param string $str New real name
2498 */
2499 public function setRealName( $str ) {
2500 $this->load();
2501 $this->mRealName = $str;
2502 }
2503
2504 /**
2505 * Get the user's current setting for a given option.
2506 *
2507 * @param string $oname The option to check
2508 * @param string $defaultOverride A default value returned if the option does not exist
2509 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2510 * @return string User's current value for the option
2511 * @see getBoolOption()
2512 * @see getIntOption()
2513 */
2514 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2515 global $wgHiddenPrefs;
2516 $this->loadOptions();
2517
2518 # We want 'disabled' preferences to always behave as the default value for
2519 # users, even if they have set the option explicitly in their settings (ie they
2520 # set it, and then it was disabled removing their ability to change it). But
2521 # we don't want to erase the preferences in the database in case the preference
2522 # is re-enabled again. So don't touch $mOptions, just override the returned value
2523 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2524 return self::getDefaultOption( $oname );
2525 }
2526
2527 if ( array_key_exists( $oname, $this->mOptions ) ) {
2528 return $this->mOptions[$oname];
2529 } else {
2530 return $defaultOverride;
2531 }
2532 }
2533
2534 /**
2535 * Get all user's options
2536 *
2537 * @return array
2538 */
2539 public function getOptions() {
2540 global $wgHiddenPrefs;
2541 $this->loadOptions();
2542 $options = $this->mOptions;
2543
2544 # We want 'disabled' preferences to always behave as the default value for
2545 # users, even if they have set the option explicitly in their settings (ie they
2546 # set it, and then it was disabled removing their ability to change it). But
2547 # we don't want to erase the preferences in the database in case the preference
2548 # is re-enabled again. So don't touch $mOptions, just override the returned value
2549 foreach ( $wgHiddenPrefs as $pref ) {
2550 $default = self::getDefaultOption( $pref );
2551 if ( $default !== null ) {
2552 $options[$pref] = $default;
2553 }
2554 }
2555
2556 return $options;
2557 }
2558
2559 /**
2560 * Get the user's current setting for a given option, as a boolean value.
2561 *
2562 * @param string $oname The option to check
2563 * @return bool User's current value for the option
2564 * @see getOption()
2565 */
2566 public function getBoolOption( $oname ) {
2567 return (bool)$this->getOption( $oname );
2568 }
2569
2570 /**
2571 * Get the user's current setting for a given option, as an integer value.
2572 *
2573 * @param string $oname The option to check
2574 * @param int $defaultOverride A default value returned if the option does not exist
2575 * @return int User's current value for the option
2576 * @see getOption()
2577 */
2578 public function getIntOption( $oname, $defaultOverride = 0 ) {
2579 $val = $this->getOption( $oname );
2580 if ( $val == '' ) {
2581 $val = $defaultOverride;
2582 }
2583 return intval( $val );
2584 }
2585
2586 /**
2587 * Set the given option for a user.
2588 *
2589 * You need to call saveSettings() to actually write to the database.
2590 *
2591 * @param string $oname The option to set
2592 * @param mixed $val New value to set
2593 */
2594 public function setOption( $oname, $val ) {
2595 $this->loadOptions();
2596
2597 // Explicitly NULL values should refer to defaults
2598 if ( is_null( $val ) ) {
2599 $val = self::getDefaultOption( $oname );
2600 }
2601
2602 $this->mOptions[$oname] = $val;
2603 }
2604
2605 /**
2606 * Get a token stored in the preferences (like the watchlist one),
2607 * resetting it if it's empty (and saving changes).
2608 *
2609 * @param string $oname The option name to retrieve the token from
2610 * @return string|bool User's current value for the option, or false if this option is disabled.
2611 * @see resetTokenFromOption()
2612 * @see getOption()
2613 */
2614 public function getTokenFromOption( $oname ) {
2615 global $wgHiddenPrefs;
2616 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2617 return false;
2618 }
2619
2620 $token = $this->getOption( $oname );
2621 if ( !$token ) {
2622 $token = $this->resetTokenFromOption( $oname );
2623 $this->saveSettings();
2624 }
2625 return $token;
2626 }
2627
2628 /**
2629 * Reset a token stored in the preferences (like the watchlist one).
2630 * *Does not* save user's preferences (similarly to setOption()).
2631 *
2632 * @param string $oname The option name to reset the token in
2633 * @return string|bool New token value, or false if this option is disabled.
2634 * @see getTokenFromOption()
2635 * @see setOption()
2636 */
2637 public function resetTokenFromOption( $oname ) {
2638 global $wgHiddenPrefs;
2639 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2640 return false;
2641 }
2642
2643 $token = MWCryptRand::generateHex( 40 );
2644 $this->setOption( $oname, $token );
2645 return $token;
2646 }
2647
2648 /**
2649 * Return a list of the types of user options currently returned by
2650 * User::getOptionKinds().
2651 *
2652 * Currently, the option kinds are:
2653 * - 'registered' - preferences which are registered in core MediaWiki or
2654 * by extensions using the UserGetDefaultOptions hook.
2655 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2656 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2657 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2658 * be used by user scripts.
2659 * - 'special' - "preferences" that are not accessible via User::getOptions
2660 * or User::setOptions.
2661 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2662 * These are usually legacy options, removed in newer versions.
2663 *
2664 * The API (and possibly others) use this function to determine the possible
2665 * option types for validation purposes, so make sure to update this when a
2666 * new option kind is added.
2667 *
2668 * @see User::getOptionKinds
2669 * @return array Option kinds
2670 */
2671 public static function listOptionKinds() {
2672 return array(
2673 'registered',
2674 'registered-multiselect',
2675 'registered-checkmatrix',
2676 'userjs',
2677 'special',
2678 'unused'
2679 );
2680 }
2681
2682 /**
2683 * Return an associative array mapping preferences keys to the kind of a preference they're
2684 * used for. Different kinds are handled differently when setting or reading preferences.
2685 *
2686 * See User::listOptionKinds for the list of valid option types that can be provided.
2687 *
2688 * @see User::listOptionKinds
2689 * @param IContextSource $context
2690 * @param array $options Assoc. array with options keys to check as keys.
2691 * Defaults to $this->mOptions.
2692 * @return array The key => kind mapping data
2693 */
2694 public function getOptionKinds( IContextSource $context, $options = null ) {
2695 $this->loadOptions();
2696 if ( $options === null ) {
2697 $options = $this->mOptions;
2698 }
2699
2700 $prefs = Preferences::getPreferences( $this, $context );
2701 $mapping = array();
2702
2703 // Pull out the "special" options, so they don't get converted as
2704 // multiselect or checkmatrix.
2705 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2706 foreach ( $specialOptions as $name => $value ) {
2707 unset( $prefs[$name] );
2708 }
2709
2710 // Multiselect and checkmatrix options are stored in the database with
2711 // one key per option, each having a boolean value. Extract those keys.
2712 $multiselectOptions = array();
2713 foreach ( $prefs as $name => $info ) {
2714 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2715 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2716 $opts = HTMLFormField::flattenOptions( $info['options'] );
2717 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2718
2719 foreach ( $opts as $value ) {
2720 $multiselectOptions["$prefix$value"] = true;
2721 }
2722
2723 unset( $prefs[$name] );
2724 }
2725 }
2726 $checkmatrixOptions = array();
2727 foreach ( $prefs as $name => $info ) {
2728 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2729 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2730 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2731 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2732 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2733
2734 foreach ( $columns as $column ) {
2735 foreach ( $rows as $row ) {
2736 $checkmatrixOptions["$prefix$column-$row"] = true;
2737 }
2738 }
2739
2740 unset( $prefs[$name] );
2741 }
2742 }
2743
2744 // $value is ignored
2745 foreach ( $options as $key => $value ) {
2746 if ( isset( $prefs[$key] ) ) {
2747 $mapping[$key] = 'registered';
2748 } elseif ( isset( $multiselectOptions[$key] ) ) {
2749 $mapping[$key] = 'registered-multiselect';
2750 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2751 $mapping[$key] = 'registered-checkmatrix';
2752 } elseif ( isset( $specialOptions[$key] ) ) {
2753 $mapping[$key] = 'special';
2754 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2755 $mapping[$key] = 'userjs';
2756 } else {
2757 $mapping[$key] = 'unused';
2758 }
2759 }
2760
2761 return $mapping;
2762 }
2763
2764 /**
2765 * Reset certain (or all) options to the site defaults
2766 *
2767 * The optional parameter determines which kinds of preferences will be reset.
2768 * Supported values are everything that can be reported by getOptionKinds()
2769 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2770 *
2771 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2772 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2773 * for backwards-compatibility.
2774 * @param IContextSource|null $context Context source used when $resetKinds
2775 * does not contain 'all', passed to getOptionKinds().
2776 * Defaults to RequestContext::getMain() when null.
2777 */
2778 public function resetOptions(
2779 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2780 IContextSource $context = null
2781 ) {
2782 $this->load();
2783 $defaultOptions = self::getDefaultOptions();
2784
2785 if ( !is_array( $resetKinds ) ) {
2786 $resetKinds = array( $resetKinds );
2787 }
2788
2789 if ( in_array( 'all', $resetKinds ) ) {
2790 $newOptions = $defaultOptions;
2791 } else {
2792 if ( $context === null ) {
2793 $context = RequestContext::getMain();
2794 }
2795
2796 $optionKinds = $this->getOptionKinds( $context );
2797 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2798 $newOptions = array();
2799
2800 // Use default values for the options that should be deleted, and
2801 // copy old values for the ones that shouldn't.
2802 foreach ( $this->mOptions as $key => $value ) {
2803 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2804 if ( array_key_exists( $key, $defaultOptions ) ) {
2805 $newOptions[$key] = $defaultOptions[$key];
2806 }
2807 } else {
2808 $newOptions[$key] = $value;
2809 }
2810 }
2811 }
2812
2813 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2814
2815 $this->mOptions = $newOptions;
2816 $this->mOptionsLoaded = true;
2817 }
2818
2819 /**
2820 * Get the user's preferred date format.
2821 * @return string User's preferred date format
2822 */
2823 public function getDatePreference() {
2824 // Important migration for old data rows
2825 if ( is_null( $this->mDatePreference ) ) {
2826 global $wgLang;
2827 $value = $this->getOption( 'date' );
2828 $map = $wgLang->getDatePreferenceMigrationMap();
2829 if ( isset( $map[$value] ) ) {
2830 $value = $map[$value];
2831 }
2832 $this->mDatePreference = $value;
2833 }
2834 return $this->mDatePreference;
2835 }
2836
2837 /**
2838 * Determine based on the wiki configuration and the user's options,
2839 * whether this user must be over HTTPS no matter what.
2840 *
2841 * @return bool
2842 */
2843 public function requiresHTTPS() {
2844 global $wgSecureLogin;
2845 if ( !$wgSecureLogin ) {
2846 return false;
2847 } else {
2848 $https = $this->getBoolOption( 'prefershttps' );
2849 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2850 if ( $https ) {
2851 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2852 }
2853 return $https;
2854 }
2855 }
2856
2857 /**
2858 * Get the user preferred stub threshold
2859 *
2860 * @return int
2861 */
2862 public function getStubThreshold() {
2863 global $wgMaxArticleSize; # Maximum article size, in Kb
2864 $threshold = $this->getIntOption( 'stubthreshold' );
2865 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2866 // If they have set an impossible value, disable the preference
2867 // so we can use the parser cache again.
2868 $threshold = 0;
2869 }
2870 return $threshold;
2871 }
2872
2873 /**
2874 * Get the permissions this user has.
2875 * @return array Array of String permission names
2876 */
2877 public function getRights() {
2878 if ( is_null( $this->mRights ) ) {
2879 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2880 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2881 // Force reindexation of rights when a hook has unset one of them
2882 $this->mRights = array_values( array_unique( $this->mRights ) );
2883 }
2884 return $this->mRights;
2885 }
2886
2887 /**
2888 * Get the list of explicit group memberships this user has.
2889 * The implicit * and user groups are not included.
2890 * @return array Array of String internal group names
2891 */
2892 public function getGroups() {
2893 $this->load();
2894 $this->loadGroups();
2895 return $this->mGroups;
2896 }
2897
2898 /**
2899 * Get the list of implicit group memberships this user has.
2900 * This includes all explicit groups, plus 'user' if logged in,
2901 * '*' for all accounts, and autopromoted groups
2902 * @param bool $recache Whether to avoid the cache
2903 * @return array Array of String internal group names
2904 */
2905 public function getEffectiveGroups( $recache = false ) {
2906 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2907 wfProfileIn( __METHOD__ );
2908 $this->mEffectiveGroups = array_unique( array_merge(
2909 $this->getGroups(), // explicit groups
2910 $this->getAutomaticGroups( $recache ) // implicit groups
2911 ) );
2912 // Hook for additional groups
2913 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2914 // Force reindexation of groups when a hook has unset one of them
2915 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2916 wfProfileOut( __METHOD__ );
2917 }
2918 return $this->mEffectiveGroups;
2919 }
2920
2921 /**
2922 * Get the list of implicit group memberships this user has.
2923 * This includes 'user' if logged in, '*' for all accounts,
2924 * and autopromoted groups
2925 * @param bool $recache Whether to avoid the cache
2926 * @return array Array of String internal group names
2927 */
2928 public function getAutomaticGroups( $recache = false ) {
2929 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2930 wfProfileIn( __METHOD__ );
2931 $this->mImplicitGroups = array( '*' );
2932 if ( $this->getId() ) {
2933 $this->mImplicitGroups[] = 'user';
2934
2935 $this->mImplicitGroups = array_unique( array_merge(
2936 $this->mImplicitGroups,
2937 Autopromote::getAutopromoteGroups( $this )
2938 ) );
2939 }
2940 if ( $recache ) {
2941 // Assure data consistency with rights/groups,
2942 // as getEffectiveGroups() depends on this function
2943 $this->mEffectiveGroups = null;
2944 }
2945 wfProfileOut( __METHOD__ );
2946 }
2947 return $this->mImplicitGroups;
2948 }
2949
2950 /**
2951 * Returns the groups the user has belonged to.
2952 *
2953 * The user may still belong to the returned groups. Compare with getGroups().
2954 *
2955 * The function will not return groups the user had belonged to before MW 1.17
2956 *
2957 * @return array Names of the groups the user has belonged to.
2958 */
2959 public function getFormerGroups() {
2960 if ( is_null( $this->mFormerGroups ) ) {
2961 $dbr = wfGetDB( DB_MASTER );
2962 $res = $dbr->select( 'user_former_groups',
2963 array( 'ufg_group' ),
2964 array( 'ufg_user' => $this->mId ),
2965 __METHOD__ );
2966 $this->mFormerGroups = array();
2967 foreach ( $res as $row ) {
2968 $this->mFormerGroups[] = $row->ufg_group;
2969 }
2970 }
2971 return $this->mFormerGroups;
2972 }
2973
2974 /**
2975 * Get the user's edit count.
2976 * @return int|null Null for anonymous users
2977 */
2978 public function getEditCount() {
2979 if ( !$this->getId() ) {
2980 return null;
2981 }
2982
2983 if ( $this->mEditCount === null ) {
2984 /* Populate the count, if it has not been populated yet */
2985 wfProfileIn( __METHOD__ );
2986 $dbr = wfGetDB( DB_SLAVE );
2987 // check if the user_editcount field has been initialized
2988 $count = $dbr->selectField(
2989 'user', 'user_editcount',
2990 array( 'user_id' => $this->mId ),
2991 __METHOD__
2992 );
2993
2994 if ( $count === null ) {
2995 // it has not been initialized. do so.
2996 $count = $this->initEditCount();
2997 }
2998 $this->mEditCount = $count;
2999 wfProfileOut( __METHOD__ );
3000 }
3001 return (int)$this->mEditCount;
3002 }
3003
3004 /**
3005 * Add the user to the given group.
3006 * This takes immediate effect.
3007 * @param string $group Name of the group to add
3008 */
3009 public function addGroup( $group ) {
3010 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
3011 $dbw = wfGetDB( DB_MASTER );
3012 if ( $this->getId() ) {
3013 $dbw->insert( 'user_groups',
3014 array(
3015 'ug_user' => $this->getID(),
3016 'ug_group' => $group,
3017 ),
3018 __METHOD__,
3019 array( 'IGNORE' ) );
3020 }
3021 }
3022 $this->loadGroups();
3023 $this->mGroups[] = $group;
3024 // In case loadGroups was not called before, we now have the right twice.
3025 // Get rid of the duplicate.
3026 $this->mGroups = array_unique( $this->mGroups );
3027
3028 // Refresh the groups caches, and clear the rights cache so it will be
3029 // refreshed on the next call to $this->getRights().
3030 $this->getEffectiveGroups( true );
3031 $this->mRights = null;
3032
3033 $this->invalidateCache();
3034 }
3035
3036 /**
3037 * Remove the user from the given group.
3038 * This takes immediate effect.
3039 * @param string $group Name of the group to remove
3040 */
3041 public function removeGroup( $group ) {
3042 $this->load();
3043 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3044 $dbw = wfGetDB( DB_MASTER );
3045 $dbw->delete( 'user_groups',
3046 array(
3047 'ug_user' => $this->getID(),
3048 'ug_group' => $group,
3049 ), __METHOD__ );
3050 // Remember that the user was in this group
3051 $dbw->insert( 'user_former_groups',
3052 array(
3053 'ufg_user' => $this->getID(),
3054 'ufg_group' => $group,
3055 ),
3056 __METHOD__,
3057 array( 'IGNORE' ) );
3058 }
3059 $this->loadGroups();
3060 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3061
3062 // Refresh the groups caches, and clear the rights cache so it will be
3063 // refreshed on the next call to $this->getRights().
3064 $this->getEffectiveGroups( true );
3065 $this->mRights = null;
3066
3067 $this->invalidateCache();
3068 }
3069
3070 /**
3071 * Get whether the user is logged in
3072 * @return bool
3073 */
3074 public function isLoggedIn() {
3075 return $this->getID() != 0;
3076 }
3077
3078 /**
3079 * Get whether the user is anonymous
3080 * @return bool
3081 */
3082 public function isAnon() {
3083 return !$this->isLoggedIn();
3084 }
3085
3086 /**
3087 * Check if user is allowed to access a feature / make an action
3088 *
3089 * @param string $permissions,... Permissions to test
3090 * @return bool True if user is allowed to perform *any* of the given actions
3091 */
3092 public function isAllowedAny( /*...*/ ) {
3093 $permissions = func_get_args();
3094 foreach ( $permissions as $permission ) {
3095 if ( $this->isAllowed( $permission ) ) {
3096 return true;
3097 }
3098 }
3099 return false;
3100 }
3101
3102 /**
3103 *
3104 * @param string $permissions,... Permissions to test
3105 * @return bool True if the user is allowed to perform *all* of the given actions
3106 */
3107 public function isAllowedAll( /*...*/ ) {
3108 $permissions = func_get_args();
3109 foreach ( $permissions as $permission ) {
3110 if ( !$this->isAllowed( $permission ) ) {
3111 return false;
3112 }
3113 }
3114 return true;
3115 }
3116
3117 /**
3118 * Internal mechanics of testing a permission
3119 * @param string $action
3120 * @return bool
3121 */
3122 public function isAllowed( $action = '' ) {
3123 if ( $action === '' ) {
3124 return true; // In the spirit of DWIM
3125 }
3126 // Patrolling may not be enabled
3127 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3128 global $wgUseRCPatrol, $wgUseNPPatrol;
3129 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3130 return false;
3131 }
3132 }
3133 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3134 // by misconfiguration: 0 == 'foo'
3135 return in_array( $action, $this->getRights(), true );
3136 }
3137
3138 /**
3139 * Check whether to enable recent changes patrol features for this user
3140 * @return bool True or false
3141 */
3142 public function useRCPatrol() {
3143 global $wgUseRCPatrol;
3144 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3145 }
3146
3147 /**
3148 * Check whether to enable new pages patrol features for this user
3149 * @return bool True or false
3150 */
3151 public function useNPPatrol() {
3152 global $wgUseRCPatrol, $wgUseNPPatrol;
3153 return (
3154 ( $wgUseRCPatrol || $wgUseNPPatrol )
3155 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3156 );
3157 }
3158
3159 /**
3160 * Get the WebRequest object to use with this object
3161 *
3162 * @return WebRequest
3163 */
3164 public function getRequest() {
3165 if ( $this->mRequest ) {
3166 return $this->mRequest;
3167 } else {
3168 global $wgRequest;
3169 return $wgRequest;
3170 }
3171 }
3172
3173 /**
3174 * Get the current skin, loading it if required
3175 * @return Skin The current skin
3176 * @todo FIXME: Need to check the old failback system [AV]
3177 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3178 */
3179 public function getSkin() {
3180 wfDeprecated( __METHOD__, '1.18' );
3181 return RequestContext::getMain()->getSkin();
3182 }
3183
3184 /**
3185 * Get a WatchedItem for this user and $title.
3186 *
3187 * @since 1.22 $checkRights parameter added
3188 * @param Title $title
3189 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3190 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3191 * @return WatchedItem
3192 */
3193 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3194 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3195
3196 if ( isset( $this->mWatchedItems[$key] ) ) {
3197 return $this->mWatchedItems[$key];
3198 }
3199
3200 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3201 $this->mWatchedItems = array();
3202 }
3203
3204 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3205 return $this->mWatchedItems[$key];
3206 }
3207
3208 /**
3209 * Check the watched status of an article.
3210 * @since 1.22 $checkRights parameter added
3211 * @param Title $title Title of the article to look at
3212 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3213 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3214 * @return bool
3215 */
3216 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3217 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3218 }
3219
3220 /**
3221 * Watch an article.
3222 * @since 1.22 $checkRights parameter added
3223 * @param Title $title Title of the article to look at
3224 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3225 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3226 */
3227 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3228 $this->getWatchedItem( $title, $checkRights )->addWatch();
3229 $this->invalidateCache();
3230 }
3231
3232 /**
3233 * Stop watching an article.
3234 * @since 1.22 $checkRights parameter added
3235 * @param Title $title Title of the article to look at
3236 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3237 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3238 */
3239 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3240 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3241 $this->invalidateCache();
3242 }
3243
3244 /**
3245 * Clear the user's notification timestamp for the given title.
3246 * If e-notif e-mails are on, they will receive notification mails on
3247 * the next change of the page if it's watched etc.
3248 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3249 * @param Title $title Title of the article to look at
3250 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3251 */
3252 public function clearNotification( &$title, $oldid = 0 ) {
3253 global $wgUseEnotif, $wgShowUpdatedMarker;
3254
3255 // Do nothing if the database is locked to writes
3256 if ( wfReadOnly() ) {
3257 return;
3258 }
3259
3260 // Do nothing if not allowed to edit the watchlist
3261 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3262 return;
3263 }
3264
3265 // If we're working on user's talk page, we should update the talk page message indicator
3266 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3267 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3268 return;
3269 }
3270
3271 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3272
3273 if ( !$oldid || !$nextid ) {
3274 // If we're looking at the latest revision, we should definitely clear it
3275 $this->setNewtalk( false );
3276 } else {
3277 // Otherwise we should update its revision, if it's present
3278 if ( $this->getNewtalk() ) {
3279 // Naturally the other one won't clear by itself
3280 $this->setNewtalk( false );
3281 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3282 }
3283 }
3284 }
3285
3286 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3287 return;
3288 }
3289
3290 if ( $this->isAnon() ) {
3291 // Nothing else to do...
3292 return;
3293 }
3294
3295 // Only update the timestamp if the page is being watched.
3296 // The query to find out if it is watched is cached both in memcached and per-invocation,
3297 // and when it does have to be executed, it can be on a slave
3298 // If this is the user's newtalk page, we always update the timestamp
3299 $force = '';
3300 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3301 $force = 'force';
3302 }
3303
3304 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3305 }
3306
3307 /**
3308 * Resets all of the given user's page-change notification timestamps.
3309 * If e-notif e-mails are on, they will receive notification mails on
3310 * the next change of any watched page.
3311 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3312 */
3313 public function clearAllNotifications() {
3314 if ( wfReadOnly() ) {
3315 return;
3316 }
3317
3318 // Do nothing if not allowed to edit the watchlist
3319 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3320 return;
3321 }
3322
3323 global $wgUseEnotif, $wgShowUpdatedMarker;
3324 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3325 $this->setNewtalk( false );
3326 return;
3327 }
3328 $id = $this->getId();
3329 if ( $id != 0 ) {
3330 $dbw = wfGetDB( DB_MASTER );
3331 $dbw->update( 'watchlist',
3332 array( /* SET */ 'wl_notificationtimestamp' => null ),
3333 array( /* WHERE */ 'wl_user' => $id ),
3334 __METHOD__
3335 );
3336 // We also need to clear here the "you have new message" notification for the own user_talk page;
3337 // it's cleared one page view later in WikiPage::doViewUpdates().
3338 }
3339 }
3340
3341 /**
3342 * Set a cookie on the user's client. Wrapper for
3343 * WebResponse::setCookie
3344 * @param string $name Name of the cookie to set
3345 * @param string $value Value to set
3346 * @param int $exp Expiration time, as a UNIX time value;
3347 * if 0 or not specified, use the default $wgCookieExpiration
3348 * @param bool $secure
3349 * true: Force setting the secure attribute when setting the cookie
3350 * false: Force NOT setting the secure attribute when setting the cookie
3351 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3352 * @param array $params Array of options sent passed to WebResponse::setcookie()
3353 */
3354 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3355 $params['secure'] = $secure;
3356 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3357 }
3358
3359 /**
3360 * Clear a cookie on the user's client
3361 * @param string $name Name of the cookie to clear
3362 * @param bool $secure
3363 * true: Force setting the secure attribute when setting the cookie
3364 * false: Force NOT setting the secure attribute when setting the cookie
3365 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3366 * @param array $params Array of options sent passed to WebResponse::setcookie()
3367 */
3368 protected function clearCookie( $name, $secure = null, $params = array() ) {
3369 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3370 }
3371
3372 /**
3373 * Set the default cookies for this session on the user's client.
3374 *
3375 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3376 * is passed.
3377 * @param bool $secure Whether to force secure/insecure cookies or use default
3378 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3379 */
3380 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3381 if ( $request === null ) {
3382 $request = $this->getRequest();
3383 }
3384
3385 $this->load();
3386 if ( 0 == $this->mId ) {
3387 return;
3388 }
3389 if ( !$this->mToken ) {
3390 // When token is empty or NULL generate a new one and then save it to the database
3391 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3392 // Simply by setting every cell in the user_token column to NULL and letting them be
3393 // regenerated as users log back into the wiki.
3394 $this->setToken();
3395 $this->saveSettings();
3396 }
3397 $session = array(
3398 'wsUserID' => $this->mId,
3399 'wsToken' => $this->mToken,
3400 'wsUserName' => $this->getName()
3401 );
3402 $cookies = array(
3403 'UserID' => $this->mId,
3404 'UserName' => $this->getName(),
3405 );
3406 if ( $rememberMe ) {
3407 $cookies['Token'] = $this->mToken;
3408 } else {
3409 $cookies['Token'] = false;
3410 }
3411
3412 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3413
3414 foreach ( $session as $name => $value ) {
3415 $request->setSessionData( $name, $value );
3416 }
3417 foreach ( $cookies as $name => $value ) {
3418 if ( $value === false ) {
3419 $this->clearCookie( $name );
3420 } else {
3421 $this->setCookie( $name, $value, 0, $secure );
3422 }
3423 }
3424
3425 /**
3426 * If wpStickHTTPS was selected, also set an insecure cookie that
3427 * will cause the site to redirect the user to HTTPS, if they access
3428 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3429 * as the one set by centralauth (bug 53538). Also set it to session, or
3430 * standard time setting, based on if rememberme was set.
3431 */
3432 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3433 $this->setCookie(
3434 'forceHTTPS',
3435 'true',
3436 $rememberMe ? 0 : null,
3437 false,
3438 array( 'prefix' => '' ) // no prefix
3439 );
3440 }
3441 }
3442
3443 /**
3444 * Log this user out.
3445 */
3446 public function logout() {
3447 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3448 $this->doLogout();
3449 }
3450 }
3451
3452 /**
3453 * Clear the user's cookies and session, and reset the instance cache.
3454 * @see logout()
3455 */
3456 public function doLogout() {
3457 $this->clearInstanceCache( 'defaults' );
3458
3459 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3460
3461 $this->clearCookie( 'UserID' );
3462 $this->clearCookie( 'Token' );
3463 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3464
3465 // Remember when user logged out, to prevent seeing cached pages
3466 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3467 }
3468
3469 /**
3470 * Save this user's settings into the database.
3471 * @todo Only rarely do all these fields need to be set!
3472 */
3473 public function saveSettings() {
3474 global $wgAuth;
3475
3476 $this->load();
3477 $this->loadPasswords();
3478 if ( wfReadOnly() ) {
3479 return;
3480 }
3481 if ( 0 == $this->mId ) {
3482 return;
3483 }
3484
3485 $this->mTouched = self::newTouchedTimestamp();
3486 if ( !$wgAuth->allowSetLocalPassword() ) {
3487 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3488 }
3489
3490 $dbw = wfGetDB( DB_MASTER );
3491 $dbw->update( 'user',
3492 array( /* SET */
3493 'user_name' => $this->mName,
3494 'user_password' => $this->mPassword->toString(),
3495 'user_newpassword' => $this->mNewpassword->toString(),
3496 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3497 'user_real_name' => $this->mRealName,
3498 'user_email' => $this->mEmail,
3499 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3500 'user_touched' => $dbw->timestamp( $this->mTouched ),
3501 'user_token' => strval( $this->mToken ),
3502 'user_email_token' => $this->mEmailToken,
3503 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3504 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3505 ), array( /* WHERE */
3506 'user_id' => $this->mId
3507 ), __METHOD__
3508 );
3509
3510 $this->saveOptions();
3511
3512 wfRunHooks( 'UserSaveSettings', array( $this ) );
3513 $this->clearSharedCache();
3514 $this->getUserPage()->invalidateCache();
3515 }
3516
3517 /**
3518 * If only this user's username is known, and it exists, return the user ID.
3519 * @return int
3520 */
3521 public function idForName() {
3522 $s = trim( $this->getName() );
3523 if ( $s === '' ) {
3524 return 0;
3525 }
3526
3527 $dbr = wfGetDB( DB_SLAVE );
3528 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3529 if ( $id === false ) {
3530 $id = 0;
3531 }
3532 return $id;
3533 }
3534
3535 /**
3536 * Add a user to the database, return the user object
3537 *
3538 * @param string $name Username to add
3539 * @param array $params Array of Strings Non-default parameters to save to
3540 * the database as user_* fields:
3541 * - password: The user's password hash. Password logins will be disabled
3542 * if this is omitted.
3543 * - newpassword: Hash for a temporary password that has been mailed to
3544 * the user.
3545 * - email: The user's email address.
3546 * - email_authenticated: The email authentication timestamp.
3547 * - real_name: The user's real name.
3548 * - options: An associative array of non-default options.
3549 * - token: Random authentication token. Do not set.
3550 * - registration: Registration timestamp. Do not set.
3551 *
3552 * @return User|null User object, or null if the username already exists.
3553 */
3554 public static function createNew( $name, $params = array() ) {
3555 $user = new User;
3556 $user->load();
3557 $user->loadPasswords();
3558 $user->setToken(); // init token
3559 if ( isset( $params['options'] ) ) {
3560 $user->mOptions = $params['options'] + (array)$user->mOptions;
3561 unset( $params['options'] );
3562 }
3563 $dbw = wfGetDB( DB_MASTER );
3564 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3565
3566 $fields = array(
3567 'user_id' => $seqVal,
3568 'user_name' => $name,
3569 'user_password' => $user->mPassword->toString(),
3570 'user_newpassword' => $user->mNewpassword->toString(),
3571 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3572 'user_email' => $user->mEmail,
3573 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3574 'user_real_name' => $user->mRealName,
3575 'user_token' => strval( $user->mToken ),
3576 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3577 'user_editcount' => 0,
3578 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3579 );
3580 foreach ( $params as $name => $value ) {
3581 $fields["user_$name"] = $value;
3582 }
3583 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3584 if ( $dbw->affectedRows() ) {
3585 $newUser = User::newFromId( $dbw->insertId() );
3586 } else {
3587 $newUser = null;
3588 }
3589 return $newUser;
3590 }
3591
3592 /**
3593 * Add this existing user object to the database. If the user already
3594 * exists, a fatal status object is returned, and the user object is
3595 * initialised with the data from the database.
3596 *
3597 * Previously, this function generated a DB error due to a key conflict
3598 * if the user already existed. Many extension callers use this function
3599 * in code along the lines of:
3600 *
3601 * $user = User::newFromName( $name );
3602 * if ( !$user->isLoggedIn() ) {
3603 * $user->addToDatabase();
3604 * }
3605 * // do something with $user...
3606 *
3607 * However, this was vulnerable to a race condition (bug 16020). By
3608 * initialising the user object if the user exists, we aim to support this
3609 * calling sequence as far as possible.
3610 *
3611 * Note that if the user exists, this function will acquire a write lock,
3612 * so it is still advisable to make the call conditional on isLoggedIn(),
3613 * and to commit the transaction after calling.
3614 *
3615 * @throws MWException
3616 * @return Status
3617 */
3618 public function addToDatabase() {
3619 $this->load();
3620 $this->loadPasswords();
3621 if ( !$this->mToken ) {
3622 $this->setToken(); // init token
3623 }
3624
3625 $this->mTouched = self::newTouchedTimestamp();
3626
3627 $dbw = wfGetDB( DB_MASTER );
3628 $inWrite = $dbw->writesOrCallbacksPending();
3629 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3630 $dbw->insert( 'user',
3631 array(
3632 'user_id' => $seqVal,
3633 'user_name' => $this->mName,
3634 'user_password' => $this->mPassword->toString(),
3635 'user_newpassword' => $this->mNewpassword->toString(),
3636 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3637 'user_email' => $this->mEmail,
3638 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3639 'user_real_name' => $this->mRealName,
3640 'user_token' => strval( $this->mToken ),
3641 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3642 'user_editcount' => 0,
3643 'user_touched' => $dbw->timestamp( $this->mTouched ),
3644 ), __METHOD__,
3645 array( 'IGNORE' )
3646 );
3647 if ( !$dbw->affectedRows() ) {
3648 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3649 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3650 if ( $inWrite ) {
3651 // Can't commit due to pending writes that may need atomicity.
3652 // This may cause some lock contention unlike the case below.
3653 $options = array( 'LOCK IN SHARE MODE' );
3654 $flags = self::READ_LOCKING;
3655 } else {
3656 // Often, this case happens early in views before any writes when
3657 // using CentralAuth. It's should be OK to commit and break the snapshot.
3658 $dbw->commit( __METHOD__, 'flush' );
3659 $options = array();
3660 $flags = 0;
3661 }
3662 $this->mId = $dbw->selectField( 'user', 'user_id',
3663 array( 'user_name' => $this->mName ), __METHOD__, $options );
3664 $loaded = false;
3665 if ( $this->mId ) {
3666 if ( $this->loadFromDatabase( $flags ) ) {
3667 $loaded = true;
3668 }
3669 }
3670 if ( !$loaded ) {
3671 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3672 "to insert user '{$this->mName}' row, but it was not present in select!" );
3673 }
3674 return Status::newFatal( 'userexists' );
3675 }
3676 $this->mId = $dbw->insertId();
3677
3678 // Clear instance cache other than user table data, which is already accurate
3679 $this->clearInstanceCache();
3680
3681 $this->saveOptions();
3682 return Status::newGood();
3683 }
3684
3685 /**
3686 * If this user is logged-in and blocked,
3687 * block any IP address they've successfully logged in from.
3688 * @return bool A block was spread
3689 */
3690 public function spreadAnyEditBlock() {
3691 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3692 return $this->spreadBlock();
3693 }
3694 return false;
3695 }
3696
3697 /**
3698 * If this (non-anonymous) user is blocked,
3699 * block the IP address they've successfully logged in from.
3700 * @return bool A block was spread
3701 */
3702 protected function spreadBlock() {
3703 wfDebug( __METHOD__ . "()\n" );
3704 $this->load();
3705 if ( $this->mId == 0 ) {
3706 return false;
3707 }
3708
3709 $userblock = Block::newFromTarget( $this->getName() );
3710 if ( !$userblock ) {
3711 return false;
3712 }
3713
3714 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3715 }
3716
3717 /**
3718 * Get whether the user is explicitly blocked from account creation.
3719 * @return bool|Block
3720 */
3721 public function isBlockedFromCreateAccount() {
3722 $this->getBlockedStatus();
3723 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3724 return $this->mBlock;
3725 }
3726
3727 # bug 13611: if the IP address the user is trying to create an account from is
3728 # blocked with createaccount disabled, prevent new account creation there even
3729 # when the user is logged in
3730 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3731 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3732 }
3733 return $this->mBlockedFromCreateAccount instanceof Block
3734 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3735 ? $this->mBlockedFromCreateAccount
3736 : false;
3737 }
3738
3739 /**
3740 * Get whether the user is blocked from using Special:Emailuser.
3741 * @return bool
3742 */
3743 public function isBlockedFromEmailuser() {
3744 $this->getBlockedStatus();
3745 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3746 }
3747
3748 /**
3749 * Get whether the user is allowed to create an account.
3750 * @return bool
3751 */
3752 public function isAllowedToCreateAccount() {
3753 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3754 }
3755
3756 /**
3757 * Get this user's personal page title.
3758 *
3759 * @return Title User's personal page title
3760 */
3761 public function getUserPage() {
3762 return Title::makeTitle( NS_USER, $this->getName() );
3763 }
3764
3765 /**
3766 * Get this user's talk page title.
3767 *
3768 * @return Title User's talk page title
3769 */
3770 public function getTalkPage() {
3771 $title = $this->getUserPage();
3772 return $title->getTalkPage();
3773 }
3774
3775 /**
3776 * Determine whether the user is a newbie. Newbies are either
3777 * anonymous IPs, or the most recently created accounts.
3778 * @return bool
3779 */
3780 public function isNewbie() {
3781 return !$this->isAllowed( 'autoconfirmed' );
3782 }
3783
3784 /**
3785 * Check to see if the given clear-text password is one of the accepted passwords
3786 * @param string $password User password
3787 * @return bool True if the given password is correct, otherwise False
3788 */
3789 public function checkPassword( $password ) {
3790 global $wgAuth, $wgLegacyEncoding;
3791
3792 $section = new ProfileSection( __METHOD__ );
3793
3794 $this->loadPasswords();
3795
3796 // Certain authentication plugins do NOT want to save
3797 // domain passwords in a mysql database, so we should
3798 // check this (in case $wgAuth->strict() is false).
3799 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3800 return true;
3801 } elseif ( $wgAuth->strict() ) {
3802 // Auth plugin doesn't allow local authentication
3803 return false;
3804 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3805 // Auth plugin doesn't allow local authentication for this user name
3806 return false;
3807 }
3808
3809 $passwordFactory = self::getPasswordFactory();
3810 if ( !$this->mPassword->equals( $password ) ) {
3811 if ( $wgLegacyEncoding ) {
3812 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3813 // Check for this with iconv
3814 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3815 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3816 return false;
3817 }
3818 } else {
3819 return false;
3820 }
3821 }
3822
3823 if ( $passwordFactory->needsUpdate( $this->mPassword ) ) {
3824 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3825 $this->saveSettings();
3826 }
3827
3828 return true;
3829 }
3830
3831 /**
3832 * Check if the given clear-text password matches the temporary password
3833 * sent by e-mail for password reset operations.
3834 *
3835 * @param string $plaintext
3836 *
3837 * @return bool True if matches, false otherwise
3838 */
3839 public function checkTemporaryPassword( $plaintext ) {
3840 global $wgNewPasswordExpiry;
3841
3842 $this->load();
3843 $this->loadPasswords();
3844 if ( $this->mNewpassword->equals( $plaintext ) ) {
3845 if ( is_null( $this->mNewpassTime ) ) {
3846 return true;
3847 }
3848 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3849 return ( time() < $expiry );
3850 } else {
3851 return false;
3852 }
3853 }
3854
3855 /**
3856 * Alias for getEditToken.
3857 * @deprecated since 1.19, use getEditToken instead.
3858 *
3859 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3860 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3861 * @return string The new edit token
3862 */
3863 public function editToken( $salt = '', $request = null ) {
3864 wfDeprecated( __METHOD__, '1.19' );
3865 return $this->getEditToken( $salt, $request );
3866 }
3867
3868 /**
3869 * Initialize (if necessary) and return a session token value
3870 * which can be used in edit forms to show that the user's
3871 * login credentials aren't being hijacked with a foreign form
3872 * submission.
3873 *
3874 * @since 1.19
3875 *
3876 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3877 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3878 * @return string The new edit token
3879 */
3880 public function getEditToken( $salt = '', $request = null ) {
3881 if ( $request == null ) {
3882 $request = $this->getRequest();
3883 }
3884
3885 if ( $this->isAnon() ) {
3886 return self::EDIT_TOKEN_SUFFIX;
3887 } else {
3888 $token = $request->getSessionData( 'wsEditToken' );
3889 if ( $token === null ) {
3890 $token = MWCryptRand::generateHex( 32 );
3891 $request->setSessionData( 'wsEditToken', $token );
3892 }
3893 if ( is_array( $salt ) ) {
3894 $salt = implode( '|', $salt );
3895 }
3896 return md5( $token . $salt ) . self::EDIT_TOKEN_SUFFIX;
3897 }
3898 }
3899
3900 /**
3901 * Generate a looking random token for various uses.
3902 *
3903 * @return string The new random token
3904 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3905 * wfRandomString for pseudo-randomness.
3906 */
3907 public static function generateToken() {
3908 return MWCryptRand::generateHex( 32 );
3909 }
3910
3911 /**
3912 * Check given value against the token value stored in the session.
3913 * A match should confirm that the form was submitted from the
3914 * user's own login session, not a form submission from a third-party
3915 * site.
3916 *
3917 * @param string $val Input value to compare
3918 * @param string $salt Optional function-specific data for hashing
3919 * @param WebRequest|null $request Object to use or null to use $wgRequest
3920 * @return bool Whether the token matches
3921 */
3922 public function matchEditToken( $val, $salt = '', $request = null ) {
3923 $sessionToken = $this->getEditToken( $salt, $request );
3924 if ( $val != $sessionToken ) {
3925 wfDebug( "User::matchEditToken: broken session data\n" );
3926 }
3927
3928 return $val == $sessionToken;
3929 }
3930
3931 /**
3932 * Check given value against the token value stored in the session,
3933 * ignoring the suffix.
3934 *
3935 * @param string $val Input value to compare
3936 * @param string $salt Optional function-specific data for hashing
3937 * @param WebRequest|null $request Object to use or null to use $wgRequest
3938 * @return bool Whether the token matches
3939 */
3940 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3941 $sessionToken = $this->getEditToken( $salt, $request );
3942 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3943 }
3944
3945 /**
3946 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3947 * mail to the user's given address.
3948 *
3949 * @param string $type Message to send, either "created", "changed" or "set"
3950 * @return Status
3951 */
3952 public function sendConfirmationMail( $type = 'created' ) {
3953 global $wgLang;
3954 $expiration = null; // gets passed-by-ref and defined in next line.
3955 $token = $this->confirmationToken( $expiration );
3956 $url = $this->confirmationTokenUrl( $token );
3957 $invalidateURL = $this->invalidationTokenUrl( $token );
3958 $this->saveSettings();
3959
3960 if ( $type == 'created' || $type === false ) {
3961 $message = 'confirmemail_body';
3962 } elseif ( $type === true ) {
3963 $message = 'confirmemail_body_changed';
3964 } else {
3965 // Messages: confirmemail_body_changed, confirmemail_body_set
3966 $message = 'confirmemail_body_' . $type;
3967 }
3968
3969 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3970 wfMessage( $message,
3971 $this->getRequest()->getIP(),
3972 $this->getName(),
3973 $url,
3974 $wgLang->timeanddate( $expiration, false ),
3975 $invalidateURL,
3976 $wgLang->date( $expiration, false ),
3977 $wgLang->time( $expiration, false ) )->text() );
3978 }
3979
3980 /**
3981 * Send an e-mail to this user's account. Does not check for
3982 * confirmed status or validity.
3983 *
3984 * @param string $subject Message subject
3985 * @param string $body Message body
3986 * @param string $from Optional From address; if unspecified, default
3987 * $wgPasswordSender will be used.
3988 * @param string $replyto Reply-To address
3989 * @return Status
3990 */
3991 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3992 if ( is_null( $from ) ) {
3993 global $wgPasswordSender;
3994 $sender = new MailAddress( $wgPasswordSender,
3995 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3996 } else {
3997 $sender = new MailAddress( $from );
3998 }
3999
4000 $to = new MailAddress( $this );
4001 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4002 }
4003
4004 /**
4005 * Generate, store, and return a new e-mail confirmation code.
4006 * A hash (unsalted, since it's used as a key) is stored.
4007 *
4008 * @note Call saveSettings() after calling this function to commit
4009 * this change to the database.
4010 *
4011 * @param string &$expiration Accepts the expiration time
4012 * @return string New token
4013 */
4014 protected function confirmationToken( &$expiration ) {
4015 global $wgUserEmailConfirmationTokenExpiry;
4016 $now = time();
4017 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4018 $expiration = wfTimestamp( TS_MW, $expires );
4019 $this->load();
4020 $token = MWCryptRand::generateHex( 32 );
4021 $hash = md5( $token );
4022 $this->mEmailToken = $hash;
4023 $this->mEmailTokenExpires = $expiration;
4024 return $token;
4025 }
4026
4027 /**
4028 * Return a URL the user can use to confirm their email address.
4029 * @param string $token Accepts the email confirmation token
4030 * @return string New token URL
4031 */
4032 protected function confirmationTokenUrl( $token ) {
4033 return $this->getTokenUrl( 'ConfirmEmail', $token );
4034 }
4035
4036 /**
4037 * Return a URL the user can use to invalidate their email address.
4038 * @param string $token Accepts the email confirmation token
4039 * @return string New token URL
4040 */
4041 protected function invalidationTokenUrl( $token ) {
4042 return $this->getTokenUrl( 'InvalidateEmail', $token );
4043 }
4044
4045 /**
4046 * Internal function to format the e-mail validation/invalidation URLs.
4047 * This uses a quickie hack to use the
4048 * hardcoded English names of the Special: pages, for ASCII safety.
4049 *
4050 * @note Since these URLs get dropped directly into emails, using the
4051 * short English names avoids insanely long URL-encoded links, which
4052 * also sometimes can get corrupted in some browsers/mailers
4053 * (bug 6957 with Gmail and Internet Explorer).
4054 *
4055 * @param string $page Special page
4056 * @param string $token Token
4057 * @return string Formatted URL
4058 */
4059 protected function getTokenUrl( $page, $token ) {
4060 // Hack to bypass localization of 'Special:'
4061 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4062 return $title->getCanonicalURL();
4063 }
4064
4065 /**
4066 * Mark the e-mail address confirmed.
4067 *
4068 * @note Call saveSettings() after calling this function to commit the change.
4069 *
4070 * @return bool
4071 */
4072 public function confirmEmail() {
4073 // Check if it's already confirmed, so we don't touch the database
4074 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4075 if ( !$this->isEmailConfirmed() ) {
4076 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4077 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4078 }
4079 return true;
4080 }
4081
4082 /**
4083 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4084 * address if it was already confirmed.
4085 *
4086 * @note Call saveSettings() after calling this function to commit the change.
4087 * @return bool Returns true
4088 */
4089 public function invalidateEmail() {
4090 $this->load();
4091 $this->mEmailToken = null;
4092 $this->mEmailTokenExpires = null;
4093 $this->setEmailAuthenticationTimestamp( null );
4094 $this->mEmail = '';
4095 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4096 return true;
4097 }
4098
4099 /**
4100 * Set the e-mail authentication timestamp.
4101 * @param string $timestamp TS_MW timestamp
4102 */
4103 public function setEmailAuthenticationTimestamp( $timestamp ) {
4104 $this->load();
4105 $this->mEmailAuthenticated = $timestamp;
4106 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4107 }
4108
4109 /**
4110 * Is this user allowed to send e-mails within limits of current
4111 * site configuration?
4112 * @return bool
4113 */
4114 public function canSendEmail() {
4115 global $wgEnableEmail, $wgEnableUserEmail;
4116 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4117 return false;
4118 }
4119 $canSend = $this->isEmailConfirmed();
4120 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4121 return $canSend;
4122 }
4123
4124 /**
4125 * Is this user allowed to receive e-mails within limits of current
4126 * site configuration?
4127 * @return bool
4128 */
4129 public function canReceiveEmail() {
4130 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4131 }
4132
4133 /**
4134 * Is this user's e-mail address valid-looking and confirmed within
4135 * limits of the current site configuration?
4136 *
4137 * @note If $wgEmailAuthentication is on, this may require the user to have
4138 * confirmed their address by returning a code or using a password
4139 * sent to the address from the wiki.
4140 *
4141 * @return bool
4142 */
4143 public function isEmailConfirmed() {
4144 global $wgEmailAuthentication;
4145 $this->load();
4146 $confirmed = true;
4147 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4148 if ( $this->isAnon() ) {
4149 return false;
4150 }
4151 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4152 return false;
4153 }
4154 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4155 return false;
4156 }
4157 return true;
4158 } else {
4159 return $confirmed;
4160 }
4161 }
4162
4163 /**
4164 * Check whether there is an outstanding request for e-mail confirmation.
4165 * @return bool
4166 */
4167 public function isEmailConfirmationPending() {
4168 global $wgEmailAuthentication;
4169 return $wgEmailAuthentication &&
4170 !$this->isEmailConfirmed() &&
4171 $this->mEmailToken &&
4172 $this->mEmailTokenExpires > wfTimestamp();
4173 }
4174
4175 /**
4176 * Get the timestamp of account creation.
4177 *
4178 * @return string|bool|null Timestamp of account creation, false for
4179 * non-existent/anonymous user accounts, or null if existing account
4180 * but information is not in database.
4181 */
4182 public function getRegistration() {
4183 if ( $this->isAnon() ) {
4184 return false;
4185 }
4186 $this->load();
4187 return $this->mRegistration;
4188 }
4189
4190 /**
4191 * Get the timestamp of the first edit
4192 *
4193 * @return string|bool Timestamp of first edit, or false for
4194 * non-existent/anonymous user accounts.
4195 */
4196 public function getFirstEditTimestamp() {
4197 if ( $this->getId() == 0 ) {
4198 return false; // anons
4199 }
4200 $dbr = wfGetDB( DB_SLAVE );
4201 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4202 array( 'rev_user' => $this->getId() ),
4203 __METHOD__,
4204 array( 'ORDER BY' => 'rev_timestamp ASC' )
4205 );
4206 if ( !$time ) {
4207 return false; // no edits
4208 }
4209 return wfTimestamp( TS_MW, $time );
4210 }
4211
4212 /**
4213 * Get the permissions associated with a given list of groups
4214 *
4215 * @param array $groups Array of Strings List of internal group names
4216 * @return array Array of Strings List of permission key names for given groups combined
4217 */
4218 public static function getGroupPermissions( $groups ) {
4219 global $wgGroupPermissions, $wgRevokePermissions;
4220 $rights = array();
4221 // grant every granted permission first
4222 foreach ( $groups as $group ) {
4223 if ( isset( $wgGroupPermissions[$group] ) ) {
4224 $rights = array_merge( $rights,
4225 // array_filter removes empty items
4226 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4227 }
4228 }
4229 // now revoke the revoked permissions
4230 foreach ( $groups as $group ) {
4231 if ( isset( $wgRevokePermissions[$group] ) ) {
4232 $rights = array_diff( $rights,
4233 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4234 }
4235 }
4236 return array_unique( $rights );
4237 }
4238
4239 /**
4240 * Get all the groups who have a given permission
4241 *
4242 * @param string $role Role to check
4243 * @return array Array of Strings List of internal group names with the given permission
4244 */
4245 public static function getGroupsWithPermission( $role ) {
4246 global $wgGroupPermissions;
4247 $allowedGroups = array();
4248 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4249 if ( self::groupHasPermission( $group, $role ) ) {
4250 $allowedGroups[] = $group;
4251 }
4252 }
4253 return $allowedGroups;
4254 }
4255
4256 /**
4257 * Check, if the given group has the given permission
4258 *
4259 * If you're wanting to check whether all users have a permission, use
4260 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4261 * from anyone.
4262 *
4263 * @since 1.21
4264 * @param string $group Group to check
4265 * @param string $role Role to check
4266 * @return bool
4267 */
4268 public static function groupHasPermission( $group, $role ) {
4269 global $wgGroupPermissions, $wgRevokePermissions;
4270 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4271 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4272 }
4273
4274 /**
4275 * Check if all users have the given permission
4276 *
4277 * @since 1.22
4278 * @param string $right Right to check
4279 * @return bool
4280 */
4281 public static function isEveryoneAllowed( $right ) {
4282 global $wgGroupPermissions, $wgRevokePermissions;
4283 static $cache = array();
4284
4285 // Use the cached results, except in unit tests which rely on
4286 // being able change the permission mid-request
4287 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4288 return $cache[$right];
4289 }
4290
4291 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4292 $cache[$right] = false;
4293 return false;
4294 }
4295
4296 // If it's revoked anywhere, then everyone doesn't have it
4297 foreach ( $wgRevokePermissions as $rights ) {
4298 if ( isset( $rights[$right] ) && $rights[$right] ) {
4299 $cache[$right] = false;
4300 return false;
4301 }
4302 }
4303
4304 // Allow extensions (e.g. OAuth) to say false
4305 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4306 $cache[$right] = false;
4307 return false;
4308 }
4309
4310 $cache[$right] = true;
4311 return true;
4312 }
4313
4314 /**
4315 * Get the localized descriptive name for a group, if it exists
4316 *
4317 * @param string $group Internal group name
4318 * @return string Localized descriptive group name
4319 */
4320 public static function getGroupName( $group ) {
4321 $msg = wfMessage( "group-$group" );
4322 return $msg->isBlank() ? $group : $msg->text();
4323 }
4324
4325 /**
4326 * Get the localized descriptive name for a member of a group, if it exists
4327 *
4328 * @param string $group Internal group name
4329 * @param string $username Username for gender (since 1.19)
4330 * @return string Localized name for group member
4331 */
4332 public static function getGroupMember( $group, $username = '#' ) {
4333 $msg = wfMessage( "group-$group-member", $username );
4334 return $msg->isBlank() ? $group : $msg->text();
4335 }
4336
4337 /**
4338 * Return the set of defined explicit groups.
4339 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4340 * are not included, as they are defined automatically, not in the database.
4341 * @return array Array of internal group names
4342 */
4343 public static function getAllGroups() {
4344 global $wgGroupPermissions, $wgRevokePermissions;
4345 return array_diff(
4346 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4347 self::getImplicitGroups()
4348 );
4349 }
4350
4351 /**
4352 * Get a list of all available permissions.
4353 * @return array Array of permission names
4354 */
4355 public static function getAllRights() {
4356 if ( self::$mAllRights === false ) {
4357 global $wgAvailableRights;
4358 if ( count( $wgAvailableRights ) ) {
4359 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4360 } else {
4361 self::$mAllRights = self::$mCoreRights;
4362 }
4363 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4364 }
4365 return self::$mAllRights;
4366 }
4367
4368 /**
4369 * Get a list of implicit groups
4370 * @return array Array of Strings Array of internal group names
4371 */
4372 public static function getImplicitGroups() {
4373 global $wgImplicitGroups;
4374
4375 $groups = $wgImplicitGroups;
4376 # Deprecated, use $wgImplictGroups instead
4377 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4378
4379 return $groups;
4380 }
4381
4382 /**
4383 * Get the title of a page describing a particular group
4384 *
4385 * @param string $group Internal group name
4386 * @return Title|bool Title of the page if it exists, false otherwise
4387 */
4388 public static function getGroupPage( $group ) {
4389 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4390 if ( $msg->exists() ) {
4391 $title = Title::newFromText( $msg->text() );
4392 if ( is_object( $title ) ) {
4393 return $title;
4394 }
4395 }
4396 return false;
4397 }
4398
4399 /**
4400 * Create a link to the group in HTML, if available;
4401 * else return the group name.
4402 *
4403 * @param string $group Internal name of the group
4404 * @param string $text The text of the link
4405 * @return string HTML link to the group
4406 */
4407 public static function makeGroupLinkHTML( $group, $text = '' ) {
4408 if ( $text == '' ) {
4409 $text = self::getGroupName( $group );
4410 }
4411 $title = self::getGroupPage( $group );
4412 if ( $title ) {
4413 return Linker::link( $title, htmlspecialchars( $text ) );
4414 } else {
4415 return $text;
4416 }
4417 }
4418
4419 /**
4420 * Create a link to the group in Wikitext, if available;
4421 * else return the group name.
4422 *
4423 * @param string $group Internal name of the group
4424 * @param string $text The text of the link
4425 * @return string Wikilink to the group
4426 */
4427 public static function makeGroupLinkWiki( $group, $text = '' ) {
4428 if ( $text == '' ) {
4429 $text = self::getGroupName( $group );
4430 }
4431 $title = self::getGroupPage( $group );
4432 if ( $title ) {
4433 $page = $title->getPrefixedText();
4434 return "[[$page|$text]]";
4435 } else {
4436 return $text;
4437 }
4438 }
4439
4440 /**
4441 * Returns an array of the groups that a particular group can add/remove.
4442 *
4443 * @param string $group The group to check for whether it can add/remove
4444 * @return array Array( 'add' => array( addablegroups ),
4445 * 'remove' => array( removablegroups ),
4446 * 'add-self' => array( addablegroups to self),
4447 * 'remove-self' => array( removable groups from self) )
4448 */
4449 public static function changeableByGroup( $group ) {
4450 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4451
4452 $groups = array(
4453 'add' => array(),
4454 'remove' => array(),
4455 'add-self' => array(),
4456 'remove-self' => array()
4457 );
4458
4459 if ( empty( $wgAddGroups[$group] ) ) {
4460 // Don't add anything to $groups
4461 } elseif ( $wgAddGroups[$group] === true ) {
4462 // You get everything
4463 $groups['add'] = self::getAllGroups();
4464 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4465 $groups['add'] = $wgAddGroups[$group];
4466 }
4467
4468 // Same thing for remove
4469 if ( empty( $wgRemoveGroups[$group] ) ) {
4470 } elseif ( $wgRemoveGroups[$group] === true ) {
4471 $groups['remove'] = self::getAllGroups();
4472 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4473 $groups['remove'] = $wgRemoveGroups[$group];
4474 }
4475
4476 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4477 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4478 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4479 if ( is_int( $key ) ) {
4480 $wgGroupsAddToSelf['user'][] = $value;
4481 }
4482 }
4483 }
4484
4485 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4486 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4487 if ( is_int( $key ) ) {
4488 $wgGroupsRemoveFromSelf['user'][] = $value;
4489 }
4490 }
4491 }
4492
4493 // Now figure out what groups the user can add to him/herself
4494 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4495 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4496 // No idea WHY this would be used, but it's there
4497 $groups['add-self'] = User::getAllGroups();
4498 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4499 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4500 }
4501
4502 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4503 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4504 $groups['remove-self'] = User::getAllGroups();
4505 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4506 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4507 }
4508
4509 return $groups;
4510 }
4511
4512 /**
4513 * Returns an array of groups that this user can add and remove
4514 * @return array Array( 'add' => array( addablegroups ),
4515 * 'remove' => array( removablegroups ),
4516 * 'add-self' => array( addablegroups to self),
4517 * 'remove-self' => array( removable groups from self) )
4518 */
4519 public function changeableGroups() {
4520 if ( $this->isAllowed( 'userrights' ) ) {
4521 // This group gives the right to modify everything (reverse-
4522 // compatibility with old "userrights lets you change
4523 // everything")
4524 // Using array_merge to make the groups reindexed
4525 $all = array_merge( User::getAllGroups() );
4526 return array(
4527 'add' => $all,
4528 'remove' => $all,
4529 'add-self' => array(),
4530 'remove-self' => array()
4531 );
4532 }
4533
4534 // Okay, it's not so simple, we will have to go through the arrays
4535 $groups = array(
4536 'add' => array(),
4537 'remove' => array(),
4538 'add-self' => array(),
4539 'remove-self' => array()
4540 );
4541 $addergroups = $this->getEffectiveGroups();
4542
4543 foreach ( $addergroups as $addergroup ) {
4544 $groups = array_merge_recursive(
4545 $groups, $this->changeableByGroup( $addergroup )
4546 );
4547 $groups['add'] = array_unique( $groups['add'] );
4548 $groups['remove'] = array_unique( $groups['remove'] );
4549 $groups['add-self'] = array_unique( $groups['add-self'] );
4550 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4551 }
4552 return $groups;
4553 }
4554
4555 /**
4556 * Increment the user's edit-count field.
4557 * Will have no effect for anonymous users.
4558 */
4559 public function incEditCount() {
4560 if ( !$this->isAnon() ) {
4561 $dbw = wfGetDB( DB_MASTER );
4562 $dbw->update(
4563 'user',
4564 array( 'user_editcount=user_editcount+1' ),
4565 array( 'user_id' => $this->getId() ),
4566 __METHOD__
4567 );
4568
4569 // Lazy initialization check...
4570 if ( $dbw->affectedRows() == 0 ) {
4571 // Now here's a goddamn hack...
4572 $dbr = wfGetDB( DB_SLAVE );
4573 if ( $dbr !== $dbw ) {
4574 // If we actually have a slave server, the count is
4575 // at least one behind because the current transaction
4576 // has not been committed and replicated.
4577 $this->initEditCount( 1 );
4578 } else {
4579 // But if DB_SLAVE is selecting the master, then the
4580 // count we just read includes the revision that was
4581 // just added in the working transaction.
4582 $this->initEditCount();
4583 }
4584 }
4585 }
4586 // edit count in user cache too
4587 $this->invalidateCache();
4588 }
4589
4590 /**
4591 * Initialize user_editcount from data out of the revision table
4592 *
4593 * @param int $add Edits to add to the count from the revision table
4594 * @return int Number of edits
4595 */
4596 protected function initEditCount( $add = 0 ) {
4597 // Pull from a slave to be less cruel to servers
4598 // Accuracy isn't the point anyway here
4599 $dbr = wfGetDB( DB_SLAVE );
4600 $count = (int)$dbr->selectField(
4601 'revision',
4602 'COUNT(rev_user)',
4603 array( 'rev_user' => $this->getId() ),
4604 __METHOD__
4605 );
4606 $count = $count + $add;
4607
4608 $dbw = wfGetDB( DB_MASTER );
4609 $dbw->update(
4610 'user',
4611 array( 'user_editcount' => $count ),
4612 array( 'user_id' => $this->getId() ),
4613 __METHOD__
4614 );
4615
4616 return $count;
4617 }
4618
4619 /**
4620 * Get the description of a given right
4621 *
4622 * @param string $right Right to query
4623 * @return string Localized description of the right
4624 */
4625 public static function getRightDescription( $right ) {
4626 $key = "right-$right";
4627 $msg = wfMessage( $key );
4628 return $msg->isBlank() ? $right : $msg->text();
4629 }
4630
4631 /**
4632 * Make a new-style password hash
4633 *
4634 * @param string $password Plain-text password
4635 * @param bool|string $salt Optional salt, may be random or the user ID.
4636 * If unspecified or false, will generate one automatically
4637 * @return string Password hash
4638 * @deprecated since 1.24, use Password class
4639 */
4640 public static function crypt( $password, $salt = false ) {
4641 wfDeprecated( __METHOD__, '1.24' );
4642 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4643 return $hash->toString();
4644 }
4645
4646 /**
4647 * Compare a password hash with a plain-text password. Requires the user
4648 * ID if there's a chance that the hash is an old-style hash.
4649 *
4650 * @param string $hash Password hash
4651 * @param string $password Plain-text password to compare
4652 * @param string|bool $userId User ID for old-style password salt
4653 *
4654 * @return bool
4655 * @deprecated since 1.24, use Password class
4656 */
4657 public static function comparePasswords( $hash, $password, $userId = false ) {
4658 wfDeprecated( __METHOD__, '1.24' );
4659
4660 // Check for *really* old password hashes that don't even have a type
4661 // The old hash format was just an md5 hex hash, with no type information
4662 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4663 global $wgPasswordSalt;
4664 if ( $wgPasswordSalt ) {
4665 $password = ":B:{$userId}:{$hash}";
4666 } else {
4667 $password = ":A:{$hash}";
4668 }
4669 }
4670
4671 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4672 return $hash->equals( $password );
4673 }
4674
4675 /**
4676 * Add a newuser log entry for this user.
4677 * Before 1.19 the return value was always true.
4678 *
4679 * @param string|bool $action Account creation type.
4680 * - String, one of the following values:
4681 * - 'create' for an anonymous user creating an account for himself.
4682 * This will force the action's performer to be the created user itself,
4683 * no matter the value of $wgUser
4684 * - 'create2' for a logged in user creating an account for someone else
4685 * - 'byemail' when the created user will receive its password by e-mail
4686 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4687 * - Boolean means whether the account was created by e-mail (deprecated):
4688 * - true will be converted to 'byemail'
4689 * - false will be converted to 'create' if this object is the same as
4690 * $wgUser and to 'create2' otherwise
4691 *
4692 * @param string $reason User supplied reason
4693 *
4694 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4695 */
4696 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4697 global $wgUser, $wgNewUserLog;
4698 if ( empty( $wgNewUserLog ) ) {
4699 return true; // disabled
4700 }
4701
4702 if ( $action === true ) {
4703 $action = 'byemail';
4704 } elseif ( $action === false ) {
4705 if ( $this->getName() == $wgUser->getName() ) {
4706 $action = 'create';
4707 } else {
4708 $action = 'create2';
4709 }
4710 }
4711
4712 if ( $action === 'create' || $action === 'autocreate' ) {
4713 $performer = $this;
4714 } else {
4715 $performer = $wgUser;
4716 }
4717
4718 $logEntry = new ManualLogEntry( 'newusers', $action );
4719 $logEntry->setPerformer( $performer );
4720 $logEntry->setTarget( $this->getUserPage() );
4721 $logEntry->setComment( $reason );
4722 $logEntry->setParameters( array(
4723 '4::userid' => $this->getId(),
4724 ) );
4725 $logid = $logEntry->insert();
4726
4727 if ( $action !== 'autocreate' ) {
4728 $logEntry->publish( $logid );
4729 }
4730
4731 return (int)$logid;
4732 }
4733
4734 /**
4735 * Add an autocreate newuser log entry for this user
4736 * Used by things like CentralAuth and perhaps other authplugins.
4737 * Consider calling addNewUserLogEntry() directly instead.
4738 *
4739 * @return bool
4740 */
4741 public function addNewUserLogEntryAutoCreate() {
4742 $this->addNewUserLogEntry( 'autocreate' );
4743
4744 return true;
4745 }
4746
4747 /**
4748 * Load the user options either from cache, the database or an array
4749 *
4750 * @param array $data Rows for the current user out of the user_properties table
4751 */
4752 protected function loadOptions( $data = null ) {
4753 global $wgContLang;
4754
4755 $this->load();
4756
4757 if ( $this->mOptionsLoaded ) {
4758 return;
4759 }
4760
4761 $this->mOptions = self::getDefaultOptions();
4762
4763 if ( !$this->getId() ) {
4764 // For unlogged-in users, load language/variant options from request.
4765 // There's no need to do it for logged-in users: they can set preferences,
4766 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4767 // so don't override user's choice (especially when the user chooses site default).
4768 $variant = $wgContLang->getDefaultVariant();
4769 $this->mOptions['variant'] = $variant;
4770 $this->mOptions['language'] = $variant;
4771 $this->mOptionsLoaded = true;
4772 return;
4773 }
4774
4775 // Maybe load from the object
4776 if ( !is_null( $this->mOptionOverrides ) ) {
4777 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4778 foreach ( $this->mOptionOverrides as $key => $value ) {
4779 $this->mOptions[$key] = $value;
4780 }
4781 } else {
4782 if ( !is_array( $data ) ) {
4783 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4784 // Load from database
4785 $dbr = wfGetDB( DB_SLAVE );
4786
4787 $res = $dbr->select(
4788 'user_properties',
4789 array( 'up_property', 'up_value' ),
4790 array( 'up_user' => $this->getId() ),
4791 __METHOD__
4792 );
4793
4794 $this->mOptionOverrides = array();
4795 $data = array();
4796 foreach ( $res as $row ) {
4797 $data[$row->up_property] = $row->up_value;
4798 }
4799 }
4800 foreach ( $data as $property => $value ) {
4801 $this->mOptionOverrides[$property] = $value;
4802 $this->mOptions[$property] = $value;
4803 }
4804 }
4805
4806 $this->mOptionsLoaded = true;
4807
4808 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4809 }
4810
4811 /**
4812 * Saves the non-default options for this user, as previously set e.g. via
4813 * setOption(), in the database's "user_properties" (preferences) table.
4814 * Usually used via saveSettings().
4815 */
4816 protected function saveOptions() {
4817 $this->loadOptions();
4818
4819 // Not using getOptions(), to keep hidden preferences in database
4820 $saveOptions = $this->mOptions;
4821
4822 // Allow hooks to abort, for instance to save to a global profile.
4823 // Reset options to default state before saving.
4824 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4825 return;
4826 }
4827
4828 $userId = $this->getId();
4829
4830 $insert_rows = array(); // all the new preference rows
4831 foreach ( $saveOptions as $key => $value ) {
4832 // Don't bother storing default values
4833 $defaultOption = self::getDefaultOption( $key );
4834 if ( ( $defaultOption === null && $value !== false && $value !== null )
4835 || $value != $defaultOption
4836 ) {
4837 $insert_rows[] = array(
4838 'up_user' => $userId,
4839 'up_property' => $key,
4840 'up_value' => $value,
4841 );
4842 }
4843 }
4844
4845 $dbw = wfGetDB( DB_MASTER );
4846
4847 $res = $dbw->select( 'user_properties',
4848 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
4849
4850 // Find prior rows that need to be removed or updated. These rows will
4851 // all be deleted (the later so that INSERT IGNORE applies the new values).
4852 $keysDelete = array();
4853 foreach ( $res as $row ) {
4854 if ( !isset( $saveOptions[$row->up_property] )
4855 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
4856 ) {
4857 $keysDelete[] = $row->up_property;
4858 }
4859 }
4860
4861 if ( count( $keysDelete ) ) {
4862 // Do the DELETE by PRIMARY KEY for prior rows.
4863 // In the past a very large portion of calls to this function are for setting
4864 // 'rememberpassword' for new accounts (a preference that has since been removed).
4865 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4866 // caused gap locks on [max user ID,+infinity) which caused high contention since
4867 // updates would pile up on each other as they are for higher (newer) user IDs.
4868 // It might not be necessary these days, but it shouldn't hurt either.
4869 $dbw->delete( 'user_properties',
4870 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
4871 }
4872 // Insert the new preference rows
4873 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4874 }
4875
4876 /**
4877 * Lazily instantiate and return a factory object for making passwords
4878 *
4879 * @return PasswordFactory
4880 */
4881 public static function getPasswordFactory() {
4882 if ( self::$mPasswordFactory === null ) {
4883 self::$mPasswordFactory = new PasswordFactory();
4884 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
4885 }
4886
4887 return self::$mPasswordFactory;
4888 }
4889
4890 /**
4891 * Provide an array of HTML5 attributes to put on an input element
4892 * intended for the user to enter a new password. This may include
4893 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4894 *
4895 * Do *not* use this when asking the user to enter his current password!
4896 * Regardless of configuration, users may have invalid passwords for whatever
4897 * reason (e.g., they were set before requirements were tightened up).
4898 * Only use it when asking for a new password, like on account creation or
4899 * ResetPass.
4900 *
4901 * Obviously, you still need to do server-side checking.
4902 *
4903 * NOTE: A combination of bugs in various browsers means that this function
4904 * actually just returns array() unconditionally at the moment. May as
4905 * well keep it around for when the browser bugs get fixed, though.
4906 *
4907 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4908 *
4909 * @return array Array of HTML attributes suitable for feeding to
4910 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4911 * That will get confused by the boolean attribute syntax used.)
4912 */
4913 public static function passwordChangeInputAttribs() {
4914 global $wgMinimalPasswordLength;
4915
4916 if ( $wgMinimalPasswordLength == 0 ) {
4917 return array();
4918 }
4919
4920 # Note that the pattern requirement will always be satisfied if the
4921 # input is empty, so we need required in all cases.
4922 #
4923 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4924 # if e-mail confirmation is being used. Since HTML5 input validation
4925 # is b0rked anyway in some browsers, just return nothing. When it's
4926 # re-enabled, fix this code to not output required for e-mail
4927 # registration.
4928 #$ret = array( 'required' );
4929 $ret = array();
4930
4931 # We can't actually do this right now, because Opera 9.6 will print out
4932 # the entered password visibly in its error message! When other
4933 # browsers add support for this attribute, or Opera fixes its support,
4934 # we can add support with a version check to avoid doing this on Opera
4935 # versions where it will be a problem. Reported to Opera as
4936 # DSK-262266, but they don't have a public bug tracker for us to follow.
4937 /*
4938 if ( $wgMinimalPasswordLength > 1 ) {
4939 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4940 $ret['title'] = wfMessage( 'passwordtooshort' )
4941 ->numParams( $wgMinimalPasswordLength )->text();
4942 }
4943 */
4944
4945 return $ret;
4946 }
4947
4948 /**
4949 * Return the list of user fields that should be selected to create
4950 * a new user object.
4951 * @return array
4952 */
4953 public static function selectFields() {
4954 return array(
4955 'user_id',
4956 'user_name',
4957 'user_real_name',
4958 'user_email',
4959 'user_touched',
4960 'user_token',
4961 'user_email_authenticated',
4962 'user_email_token',
4963 'user_email_token_expires',
4964 'user_registration',
4965 'user_editcount',
4966 );
4967 }
4968
4969 /**
4970 * Factory function for fatal permission-denied errors
4971 *
4972 * @since 1.22
4973 * @param string $permission User right required
4974 * @return Status
4975 */
4976 static function newFatalPermissionDeniedStatus( $permission ) {
4977 global $wgLang;
4978
4979 $groups = array_map(
4980 array( 'User', 'makeGroupLinkWiki' ),
4981 User::getGroupsWithPermission( $permission )
4982 );
4983
4984 if ( $groups ) {
4985 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4986 } else {
4987 return Status::newFatal( 'badaccess-group0' );
4988 }
4989 }
4990 }