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