Missing rights: move-rootuserpages, move-subpages
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 * @file
5 */
6
7 /**
8 * \int Number of characters in user_token field.
9 * @ingroup Constants
10 */
11 define( 'USER_TOKEN_LENGTH', 32 );
12
13 /**
14 * \int Serialized record version.
15 * @ingroup Constants
16 */
17 define( 'MW_USER_VERSION', 6 );
18
19 /**
20 * \string Some punctuation to prevent editing from broken text-mangling proxies.
21 * @ingroup Constants
22 */
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
24
25 /**
26 * Thrown by User::setPassword() on error.
27 * @ingroup Exception
28 */
29 class PasswordError extends MWException {
30 // NOP
31 }
32
33 /**
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
41 * of the database.
42 */
43 class User {
44
45 /**
46 * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
47 * preferences that are displayed by Special:Preferences as checkboxes.
48 * This list can be extended via the UserToggles hook or by
49 * $wgContLang::getExtraUserToggles().
50 * @showinitializer
51 */
52 public static $mToggles = array(
53 'highlightbroken',
54 'justify',
55 'hideminor',
56 'extendwatchlist',
57 'usenewrc',
58 'numberheadings',
59 'showtoolbar',
60 'editondblclick',
61 'editsection',
62 'editsectiononrightclick',
63 'showtoc',
64 'rememberpassword',
65 'editwidth',
66 'watchcreations',
67 'watchdefault',
68 'watchmoves',
69 'watchdeletion',
70 'minordefault',
71 'previewontop',
72 'previewonfirst',
73 'nocache',
74 'enotifwatchlistpages',
75 'enotifusertalkpages',
76 'enotifminoredits',
77 'enotifrevealaddr',
78 'shownumberswatching',
79 'fancysig',
80 'externaleditor',
81 'externaldiff',
82 'showjumplinks',
83 'uselivepreview',
84 'forceeditsummary',
85 'watchlisthideminor',
86 'watchlisthidebots',
87 'watchlisthideown',
88 'watchlisthideanons',
89 'watchlisthideliu',
90 'ccmeonemails',
91 'diffonly',
92 'showhiddencats',
93 'noconvertlink',
94 'norollbackdiff',
95 );
96
97 /**
98 * \type{\arrayof{\string}} List of member variables which are saved to the
99 * shared cache (memcached). Any operation which changes the
100 * corresponding database fields must call a cache-clearing function.
101 * @showinitializer
102 */
103 static $mCacheVars = array(
104 // user table
105 'mId',
106 'mName',
107 'mRealName',
108 'mPassword',
109 'mNewpassword',
110 'mNewpassTime',
111 'mEmail',
112 'mOptions',
113 'mTouched',
114 'mToken',
115 'mEmailAuthenticated',
116 'mEmailToken',
117 'mEmailTokenExpires',
118 'mRegistration',
119 'mEditCount',
120 // user_group table
121 'mGroups',
122 );
123
124 /**
125 * \type{\arrayof{\string}} Core rights.
126 * Each of these should have a corresponding message of the form
127 * "right-$right".
128 * @showinitializer
129 */
130 static $mCoreRights = array(
131 'apihighlimits',
132 'autoconfirmed',
133 'autopatrol',
134 'bigdelete',
135 'block',
136 'blockemail',
137 'bot',
138 'browsearchive',
139 'createaccount',
140 'createpage',
141 'createtalk',
142 'delete',
143 'deletedhistory',
144 'edit',
145 'editinterface',
146 'editusercssjs',
147 'import',
148 'importupload',
149 'interwiki',
150 'ipblock-exempt',
151 'markbotedits',
152 'minoredit',
153 'move',
154 'move-rootuserpages',
155 'move-subpages',
156 'nominornewtalk',
157 'noratelimit',
158 'patrol',
159 'protect',
160 'proxyunbannable',
161 'purge',
162 'read',
163 'reupload',
164 'reupload-shared',
165 'rollback',
166 'siteadmin',
167 'suppressredirect',
168 'trackback',
169 'undelete',
170 'unwatchedpages',
171 'upload',
172 'upload_by_url',
173 'userrights',
174 );
175 /**
176 * \string Cached results of getAllRights()
177 */
178 static $mAllRights = false;
179
180 /** @name Cache variables */
181 //@{
182 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
183 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
184 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
185 //@}
186
187 /**
188 * \bool Whether the cache variables have been loaded.
189 */
190 var $mDataLoaded, $mAuthLoaded;
191
192 /**
193 * \string Initialization data source if mDataLoaded==false. May be one of:
194 * - 'defaults' anonymous user initialised from class defaults
195 * - 'name' initialise from mName
196 * - 'id' initialise from mId
197 * - 'session' log in from cookies or session if possible
198 *
199 * Use the User::newFrom*() family of functions to set this.
200 */
201 var $mFrom;
202
203 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
204 //@{
205 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
206 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
207 $mLocked, $mHideName;
208 //@}
209
210 /**
211 * Lightweight constructor for an anonymous user.
212 * Use the User::newFrom* factory functions for other kinds of users.
213 *
214 * @see newFromName()
215 * @see newFromId()
216 * @see newFromConfirmationCode()
217 * @see newFromSession()
218 * @see newFromRow()
219 */
220 function User() {
221 $this->clearInstanceCache( 'defaults' );
222 }
223
224 /**
225 * Load the user table data for this object from the source given by mFrom.
226 */
227 function load() {
228 if ( $this->mDataLoaded ) {
229 return;
230 }
231 wfProfileIn( __METHOD__ );
232
233 # Set it now to avoid infinite recursion in accessors
234 $this->mDataLoaded = true;
235
236 switch ( $this->mFrom ) {
237 case 'defaults':
238 $this->loadDefaults();
239 break;
240 case 'name':
241 $this->mId = self::idFromName( $this->mName );
242 if ( !$this->mId ) {
243 # Nonexistent user placeholder object
244 $this->loadDefaults( $this->mName );
245 } else {
246 $this->loadFromId();
247 }
248 break;
249 case 'id':
250 $this->loadFromId();
251 break;
252 case 'session':
253 $this->loadFromSession();
254 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
255 break;
256 default:
257 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
258 }
259 wfProfileOut( __METHOD__ );
260 }
261
262 /**
263 * Load user table data, given mId has already been set.
264 * @return \bool false if the ID does not exist, true otherwise
265 * @private
266 */
267 function loadFromId() {
268 global $wgMemc;
269 if ( $this->mId == 0 ) {
270 $this->loadDefaults();
271 return false;
272 }
273
274 # Try cache
275 $key = wfMemcKey( 'user', 'id', $this->mId );
276 $data = $wgMemc->get( $key );
277 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
278 # Object is expired, load from DB
279 $data = false;
280 }
281
282 if ( !$data ) {
283 wfDebug( "Cache miss for user {$this->mId}\n" );
284 # Load from DB
285 if ( !$this->loadFromDatabase() ) {
286 # Can't load from ID, user is anonymous
287 return false;
288 }
289 $this->saveToCache();
290 } else {
291 wfDebug( "Got user {$this->mId} from cache\n" );
292 # Restore from cache
293 foreach ( self::$mCacheVars as $name ) {
294 $this->$name = $data[$name];
295 }
296 }
297 return true;
298 }
299
300 /**
301 * Save user data to the shared cache
302 */
303 function saveToCache() {
304 $this->load();
305 $this->loadGroups();
306 if ( $this->isAnon() ) {
307 // Anonymous users are uncached
308 return;
309 }
310 $data = array();
311 foreach ( self::$mCacheVars as $name ) {
312 $data[$name] = $this->$name;
313 }
314 $data['mVersion'] = MW_USER_VERSION;
315 $key = wfMemcKey( 'user', 'id', $this->mId );
316 global $wgMemc;
317 $wgMemc->set( $key, $data );
318 }
319
320
321 /** @name newFrom*() static factory methods */
322 //@{
323
324 /**
325 * Static factory method for creation from username.
326 *
327 * This is slightly less efficient than newFromId(), so use newFromId() if
328 * you have both an ID and a name handy.
329 *
330 * @param $name \string Username, validated by Title::newFromText()
331 * @param $validate \mixed Validate username. Takes the same parameters as
332 * User::getCanonicalName(), except that true is accepted as an alias
333 * for 'valid', for BC.
334 *
335 * @return \type{User} The User object, or null if the username is invalid. If the
336 * username is not present in the database, the result will be a user object
337 * with a name, zero user ID and default settings.
338 */
339 static function newFromName( $name, $validate = 'valid' ) {
340 if ( $validate === true ) {
341 $validate = 'valid';
342 }
343 $name = self::getCanonicalName( $name, $validate );
344 if ( $name === false ) {
345 return null;
346 } else {
347 # Create unloaded user object
348 $u = new User;
349 $u->mName = $name;
350 $u->mFrom = 'name';
351 return $u;
352 }
353 }
354
355 /**
356 * Static factory method for creation from a given user ID.
357 *
358 * @param $id \int Valid user ID
359 * @return \type{User} The corresponding User object
360 */
361 static function newFromId( $id ) {
362 $u = new User;
363 $u->mId = $id;
364 $u->mFrom = 'id';
365 return $u;
366 }
367
368 /**
369 * Factory method to fetch whichever user has a given email confirmation code.
370 * This code is generated when an account is created or its e-mail address
371 * has changed.
372 *
373 * If the code is invalid or has expired, returns NULL.
374 *
375 * @param $code \string Confirmation code
376 * @return \type{User}
377 */
378 static function newFromConfirmationCode( $code ) {
379 $dbr = wfGetDB( DB_SLAVE );
380 $id = $dbr->selectField( 'user', 'user_id', array(
381 'user_email_token' => md5( $code ),
382 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
383 ) );
384 if( $id !== false ) {
385 return User::newFromId( $id );
386 } else {
387 return null;
388 }
389 }
390
391 /**
392 * Create a new user object using data from session or cookies. If the
393 * login credentials are invalid, the result is an anonymous user.
394 *
395 * @return \type{User}
396 */
397 static function newFromSession() {
398 $user = new User;
399 $user->mFrom = 'session';
400 return $user;
401 }
402
403 /**
404 * Create a new user object from a user row.
405 * The row should have all fields from the user table in it.
406 * @param $row array A row from the user table
407 * @return \type{User}
408 */
409 static function newFromRow( $row ) {
410 $user = new User;
411 $user->loadFromRow( $row );
412 return $user;
413 }
414
415 //@}
416
417
418 /**
419 * Get the username corresponding to a given user ID
420 * @param $id \int User ID
421 * @return \string The corresponding username
422 */
423 static function whoIs( $id ) {
424 $dbr = wfGetDB( DB_SLAVE );
425 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
426 }
427
428 /**
429 * Get the real name of a user given their user ID
430 *
431 * @param $id \int User ID
432 * @return \string The corresponding user's real name
433 */
434 static function whoIsReal( $id ) {
435 $dbr = wfGetDB( DB_SLAVE );
436 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
437 }
438
439 /**
440 * Get database id given a user name
441 * @param $name \string Username
442 * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
443 */
444 static function idFromName( $name ) {
445 $nt = Title::makeTitleSafe( NS_USER, $name );
446 if( is_null( $nt ) ) {
447 # Illegal name
448 return null;
449 }
450 $dbr = wfGetDB( DB_SLAVE );
451 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
452
453 if ( $s === false ) {
454 return 0;
455 } else {
456 return $s->user_id;
457 }
458 }
459
460 /**
461 * Does the string match an anonymous IPv4 address?
462 *
463 * This function exists for username validation, in order to reject
464 * usernames which are similar in form to IP addresses. Strings such
465 * as 300.300.300.300 will return true because it looks like an IP
466 * address, despite not being strictly valid.
467 *
468 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
469 * address because the usemod software would "cloak" anonymous IP
470 * addresses like this, if we allowed accounts like this to be created
471 * new users could get the old edits of these anonymous users.
472 *
473 * @param $name \string String to match
474 * @return \bool True or false
475 */
476 static function isIP( $name ) {
477 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
478 }
479
480 /**
481 * Is the input a valid username?
482 *
483 * Checks if the input is a valid username, we don't want an empty string,
484 * an IP address, anything that containins slashes (would mess up subpages),
485 * is longer than the maximum allowed username size or doesn't begin with
486 * a capital letter.
487 *
488 * @param $name \string String to match
489 * @return \bool True or false
490 */
491 static function isValidUserName( $name ) {
492 global $wgContLang, $wgMaxNameChars;
493
494 if ( $name == ''
495 || User::isIP( $name )
496 || strpos( $name, '/' ) !== false
497 || strlen( $name ) > $wgMaxNameChars
498 || $name != $wgContLang->ucfirst( $name ) ) {
499 wfDebugLog( 'username', __METHOD__ .
500 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
501 return false;
502 }
503
504 // Ensure that the name can't be misresolved as a different title,
505 // such as with extra namespace keys at the start.
506 $parsed = Title::newFromText( $name );
507 if( is_null( $parsed )
508 || $parsed->getNamespace()
509 || strcmp( $name, $parsed->getPrefixedText() ) ) {
510 wfDebugLog( 'username', __METHOD__ .
511 ": '$name' invalid due to ambiguous prefixes" );
512 return false;
513 }
514
515 // Check an additional blacklist of troublemaker characters.
516 // Should these be merged into the title char list?
517 $unicodeBlacklist = '/[' .
518 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
519 '\x{00a0}' . # non-breaking space
520 '\x{2000}-\x{200f}' . # various whitespace
521 '\x{2028}-\x{202f}' . # breaks and control chars
522 '\x{3000}' . # ideographic space
523 '\x{e000}-\x{f8ff}' . # private use
524 ']/u';
525 if( preg_match( $unicodeBlacklist, $name ) ) {
526 wfDebugLog( 'username', __METHOD__ .
527 ": '$name' invalid due to blacklisted characters" );
528 return false;
529 }
530
531 return true;
532 }
533
534 /**
535 * Usernames which fail to pass this function will be blocked
536 * from user login and new account registrations, but may be used
537 * internally by batch processes.
538 *
539 * If an account already exists in this form, login will be blocked
540 * by a failure to pass this function.
541 *
542 * @param $name \string String to match
543 * @return \bool True or false
544 */
545 static function isUsableName( $name ) {
546 global $wgReservedUsernames;
547 // Must be a valid username, obviously ;)
548 if ( !self::isValidUserName( $name ) ) {
549 return false;
550 }
551
552 static $reservedUsernames = false;
553 if ( !$reservedUsernames ) {
554 $reservedUsernames = $wgReservedUsernames;
555 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
556 }
557
558 // Certain names may be reserved for batch processes.
559 foreach ( $reservedUsernames as $reserved ) {
560 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
561 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
562 }
563 if ( $reserved == $name ) {
564 return false;
565 }
566 }
567 return true;
568 }
569
570 /**
571 * Usernames which fail to pass this function will be blocked
572 * from new account registrations, but may be used internally
573 * either by batch processes or by user accounts which have
574 * already been created.
575 *
576 * Additional character blacklisting may be added here
577 * rather than in isValidUserName() to avoid disrupting
578 * existing accounts.
579 *
580 * @param $name \string String to match
581 * @return \bool True or false
582 */
583 static function isCreatableName( $name ) {
584 return
585 self::isUsableName( $name ) &&
586
587 // Registration-time character blacklisting...
588 strpos( $name, '@' ) === false;
589 }
590
591 /**
592 * Is the input a valid password for this user?
593 *
594 * @param $password \string Desired password
595 * @return \bool True or false
596 */
597 function isValidPassword( $password ) {
598 global $wgMinimalPasswordLength, $wgContLang;
599
600 $result = null;
601 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
602 return $result;
603 if( $result === false )
604 return false;
605
606 // Password needs to be long enough, and can't be the same as the username
607 return strlen( $password ) >= $wgMinimalPasswordLength
608 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
609 }
610
611 /**
612 * Does a string look like an e-mail address?
613 *
614 * There used to be a regular expression here, it got removed because it
615 * rejected valid addresses. Actually just check if there is '@' somewhere
616 * in the given address.
617 *
618 * @todo Check for RFC 2822 compilance (bug 959)
619 *
620 * @param $addr \string E-mail address
621 * @return \bool True or false
622 */
623 public static function isValidEmailAddr( $addr ) {
624 $result = null;
625 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
626 return $result;
627 }
628
629 return strpos( $addr, '@' ) !== false;
630 }
631
632 /**
633 * Given unvalidated user input, return a canonical username, or false if
634 * the username is invalid.
635 * @param $name \string User input
636 * @param $validate \types{\string,\bool} Type of validation to use:
637 * - false No validation
638 * - 'valid' Valid for batch processes
639 * - 'usable' Valid for batch processes and login
640 * - 'creatable' Valid for batch processes, login and account creation
641 */
642 static function getCanonicalName( $name, $validate = 'valid' ) {
643 # Force usernames to capital
644 global $wgContLang;
645 $name = $wgContLang->ucfirst( $name );
646
647 # Reject names containing '#'; these will be cleaned up
648 # with title normalisation, but then it's too late to
649 # check elsewhere
650 if( strpos( $name, '#' ) !== false )
651 return false;
652
653 # Clean up name according to title rules
654 $t = ($validate === 'valid') ?
655 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
656 # Check for invalid titles
657 if( is_null( $t ) ) {
658 return false;
659 }
660
661 # Reject various classes of invalid names
662 $name = $t->getText();
663 global $wgAuth;
664 $name = $wgAuth->getCanonicalName( $t->getText() );
665
666 switch ( $validate ) {
667 case false:
668 break;
669 case 'valid':
670 if ( !User::isValidUserName( $name ) ) {
671 $name = false;
672 }
673 break;
674 case 'usable':
675 if ( !User::isUsableName( $name ) ) {
676 $name = false;
677 }
678 break;
679 case 'creatable':
680 if ( !User::isCreatableName( $name ) ) {
681 $name = false;
682 }
683 break;
684 default:
685 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
686 }
687 return $name;
688 }
689
690 /**
691 * Count the number of edits of a user
692 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
693 *
694 * @param $uid \int User ID to check
695 * @return \int The user's edit count
696 */
697 static function edits( $uid ) {
698 wfProfileIn( __METHOD__ );
699 $dbr = wfGetDB( DB_SLAVE );
700 // check if the user_editcount field has been initialized
701 $field = $dbr->selectField(
702 'user', 'user_editcount',
703 array( 'user_id' => $uid ),
704 __METHOD__
705 );
706
707 if( $field === null ) { // it has not been initialized. do so.
708 $dbw = wfGetDB( DB_MASTER );
709 $count = $dbr->selectField(
710 'revision', 'count(*)',
711 array( 'rev_user' => $uid ),
712 __METHOD__
713 );
714 $dbw->update(
715 'user',
716 array( 'user_editcount' => $count ),
717 array( 'user_id' => $uid ),
718 __METHOD__
719 );
720 } else {
721 $count = $field;
722 }
723 wfProfileOut( __METHOD__ );
724 return $count;
725 }
726
727 /**
728 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
729 * @todo hash random numbers to improve security, like generateToken()
730 *
731 * @return \string New random password
732 */
733 static function randomPassword() {
734 global $wgMinimalPasswordLength;
735 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
736 $l = strlen( $pwchars ) - 1;
737
738 $pwlength = max( 7, $wgMinimalPasswordLength );
739 $digit = mt_rand(0, $pwlength - 1);
740 $np = '';
741 for ( $i = 0; $i < $pwlength; $i++ ) {
742 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
743 }
744 return $np;
745 }
746
747 /**
748 * Set cached properties to default.
749 *
750 * @note This no longer clears uncached lazy-initialised properties;
751 * the constructor does that instead.
752 * @private
753 */
754 function loadDefaults( $name = false ) {
755 wfProfileIn( __METHOD__ );
756
757 global $wgCookiePrefix;
758
759 $this->mId = 0;
760 $this->mName = $name;
761 $this->mRealName = '';
762 $this->mPassword = $this->mNewpassword = '';
763 $this->mNewpassTime = null;
764 $this->mEmail = '';
765 $this->mOptions = null; # Defer init
766
767 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
768 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
769 } else {
770 $this->mTouched = '0'; # Allow any pages to be cached
771 }
772
773 $this->setToken(); # Random
774 $this->mEmailAuthenticated = null;
775 $this->mEmailToken = '';
776 $this->mEmailTokenExpires = null;
777 $this->mRegistration = wfTimestamp( TS_MW );
778 $this->mGroups = array();
779
780 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
781
782 wfProfileOut( __METHOD__ );
783 }
784
785 /**
786 * @deprecated Use wfSetupSession().
787 */
788 function SetupSession() {
789 wfDeprecated( __METHOD__ );
790 wfSetupSession();
791 }
792
793 /**
794 * Load user data from the session or login cookie. If there are no valid
795 * credentials, initialises the user as an anonymous user.
796 * @return \bool True if the user is logged in, false otherwise.
797 */
798 private function loadFromSession() {
799 global $wgMemc, $wgCookiePrefix;
800
801 $result = null;
802 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
803 if ( $result !== null ) {
804 return $result;
805 }
806
807 if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
808 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
809 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
810 $this->loadDefaults(); // Possible collision!
811 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
812 cookie user ID ($sId) don't match!" );
813 return false;
814 }
815 $_SESSION['wsUserID'] = $sId;
816 } else if ( isset( $_SESSION['wsUserID'] ) ) {
817 if ( $_SESSION['wsUserID'] != 0 ) {
818 $sId = $_SESSION['wsUserID'];
819 } else {
820 $this->loadDefaults();
821 return false;
822 }
823 } else {
824 $this->loadDefaults();
825 return false;
826 }
827
828 if ( isset( $_SESSION['wsUserName'] ) ) {
829 $sName = $_SESSION['wsUserName'];
830 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
831 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
832 $_SESSION['wsUserName'] = $sName;
833 } else {
834 $this->loadDefaults();
835 return false;
836 }
837
838 $passwordCorrect = FALSE;
839 $this->mId = $sId;
840 if ( !$this->loadFromId() ) {
841 # Not a valid ID, loadFromId has switched the object to anon for us
842 return false;
843 }
844
845 if ( isset( $_SESSION['wsToken'] ) ) {
846 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
847 $from = 'session';
848 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
849 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
850 $from = 'cookie';
851 } else {
852 # No session or persistent login cookie
853 $this->loadDefaults();
854 return false;
855 }
856
857 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
858 $_SESSION['wsToken'] = $this->mToken;
859 wfDebug( "Logged in from $from\n" );
860 return true;
861 } else {
862 # Invalid credentials
863 wfDebug( "Can't log in from $from, invalid credentials\n" );
864 $this->loadDefaults();
865 return false;
866 }
867 }
868
869 /**
870 * Load user and user_group data from the database.
871 * $this::mId must be set, this is how the user is identified.
872 *
873 * @return \bool True if the user exists, false if the user is anonymous
874 * @private
875 */
876 function loadFromDatabase() {
877 # Paranoia
878 $this->mId = intval( $this->mId );
879
880 /** Anonymous user */
881 if( !$this->mId ) {
882 $this->loadDefaults();
883 return false;
884 }
885
886 $dbr = wfGetDB( DB_MASTER );
887 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
888
889 if ( $s !== false ) {
890 # Initialise user table data
891 $this->loadFromRow( $s );
892 $this->mGroups = null; // deferred
893 $this->getEditCount(); // revalidation for nulls
894 return true;
895 } else {
896 # Invalid user_id
897 $this->mId = 0;
898 $this->loadDefaults();
899 return false;
900 }
901 }
902
903 /**
904 * Initialize this object from a row from the user table.
905 *
906 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
907 */
908 function loadFromRow( $row ) {
909 $this->mDataLoaded = true;
910
911 if ( isset( $row->user_id ) ) {
912 $this->mId = $row->user_id;
913 }
914 $this->mName = $row->user_name;
915 $this->mRealName = $row->user_real_name;
916 $this->mPassword = $row->user_password;
917 $this->mNewpassword = $row->user_newpassword;
918 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
919 $this->mEmail = $row->user_email;
920 $this->decodeOptions( $row->user_options );
921 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
922 $this->mToken = $row->user_token;
923 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
924 $this->mEmailToken = $row->user_email_token;
925 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
926 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
927 $this->mEditCount = $row->user_editcount;
928 }
929
930 /**
931 * Load the groups from the database if they aren't already loaded.
932 * @private
933 */
934 function loadGroups() {
935 if ( is_null( $this->mGroups ) ) {
936 $dbr = wfGetDB( DB_MASTER );
937 $res = $dbr->select( 'user_groups',
938 array( 'ug_group' ),
939 array( 'ug_user' => $this->mId ),
940 __METHOD__ );
941 $this->mGroups = array();
942 while( $row = $dbr->fetchObject( $res ) ) {
943 $this->mGroups[] = $row->ug_group;
944 }
945 }
946 }
947
948 /**
949 * Clear various cached data stored in this object.
950 * @param $reloadFrom \string Reload user and user_groups table data from a
951 * given source. May be "name", "id", "defaults", "session", or false for
952 * no reload.
953 */
954 function clearInstanceCache( $reloadFrom = false ) {
955 $this->mNewtalk = -1;
956 $this->mDatePreference = null;
957 $this->mBlockedby = -1; # Unset
958 $this->mHash = false;
959 $this->mSkin = null;
960 $this->mRights = null;
961 $this->mEffectiveGroups = null;
962
963 if ( $reloadFrom ) {
964 $this->mDataLoaded = false;
965 $this->mFrom = $reloadFrom;
966 }
967 }
968
969 /**
970 * Combine the language default options with any site-specific options
971 * and add the default language variants.
972 *
973 * @return \type{\arrayof{\string}} Array of options
974 */
975 static function getDefaultOptions() {
976 global $wgNamespacesToBeSearchedDefault;
977 /**
978 * Site defaults will override the global/language defaults
979 */
980 global $wgDefaultUserOptions, $wgContLang;
981 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
982
983 /**
984 * default language setting
985 */
986 $variant = $wgContLang->getPreferredVariant( false );
987 $defOpt['variant'] = $variant;
988 $defOpt['language'] = $variant;
989
990 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
991 $defOpt['searchNs'.$nsnum] = $val;
992 }
993 return $defOpt;
994 }
995
996 /**
997 * Get a given default option value.
998 *
999 * @param $opt \string Name of option to retrieve
1000 * @return \string Default option value
1001 */
1002 public static function getDefaultOption( $opt ) {
1003 $defOpts = self::getDefaultOptions();
1004 if( isset( $defOpts[$opt] ) ) {
1005 return $defOpts[$opt];
1006 } else {
1007 return '';
1008 }
1009 }
1010
1011 /**
1012 * Get a list of user toggle names
1013 * @return \type{\arrayof{\string}} Array of user toggle names
1014 */
1015 static function getToggles() {
1016 global $wgContLang;
1017 $extraToggles = array();
1018 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1019 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1020 }
1021
1022
1023 /**
1024 * Get blocking information
1025 * @private
1026 * @param $bFromSlave \bool Whether to check the slave database first. To
1027 * improve performance, non-critical checks are done
1028 * against slaves. Check when actually saving should be
1029 * done against master.
1030 */
1031 function getBlockedStatus( $bFromSlave = true ) {
1032 global $wgEnableSorbs, $wgProxyWhitelist;
1033
1034 if ( -1 != $this->mBlockedby ) {
1035 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1036 return;
1037 }
1038
1039 wfProfileIn( __METHOD__ );
1040 wfDebug( __METHOD__.": checking...\n" );
1041
1042 // Initialize data...
1043 // Otherwise something ends up stomping on $this->mBlockedby when
1044 // things get lazy-loaded later, causing false positive block hits
1045 // due to -1 !== 0. Probably session-related... Nothing should be
1046 // overwriting mBlockedby, surely?
1047 $this->load();
1048
1049 $this->mBlockedby = 0;
1050 $this->mHideName = 0;
1051 $this->mAllowUsertalk = 0;
1052 $ip = wfGetIP();
1053
1054 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1055 # Exempt from all types of IP-block
1056 $ip = '';
1057 }
1058
1059 # User/IP blocking
1060 $this->mBlock = new Block();
1061 $this->mBlock->fromMaster( !$bFromSlave );
1062 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1063 wfDebug( __METHOD__.": Found block.\n" );
1064 $this->mBlockedby = $this->mBlock->mBy;
1065 $this->mBlockreason = $this->mBlock->mReason;
1066 $this->mHideName = $this->mBlock->mHideName;
1067 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1068 if ( $this->isLoggedIn() ) {
1069 $this->spreadBlock();
1070 }
1071 } else {
1072 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1073 // apply to users. Note that the existence of $this->mBlock is not used to
1074 // check for edit blocks, $this->mBlockedby is instead.
1075 }
1076
1077 # Proxy blocking
1078 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1079 # Local list
1080 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1081 $this->mBlockedby = wfMsg( 'proxyblocker' );
1082 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1083 }
1084
1085 # DNSBL
1086 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1087 if ( $this->inSorbsBlacklist( $ip ) ) {
1088 $this->mBlockedby = wfMsg( 'sorbs' );
1089 $this->mBlockreason = wfMsg( 'sorbsreason' );
1090 }
1091 }
1092 }
1093
1094 # Extensions
1095 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1096
1097 wfProfileOut( __METHOD__ );
1098 }
1099
1100 /**
1101 * Whether the given IP is in the SORBS blacklist.
1102 *
1103 * @param $ip \string IP to check
1104 * @return \bool True if blacklisted.
1105 */
1106 function inSorbsBlacklist( $ip ) {
1107 global $wgEnableSorbs, $wgSorbsUrl;
1108
1109 return $wgEnableSorbs &&
1110 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1111 }
1112
1113 /**
1114 * Whether the given IP is in a given DNS blacklist.
1115 *
1116 * @param $ip \string IP to check
1117 * @param $base \string URL of the DNS blacklist
1118 * @return \bool True if blacklisted.
1119 */
1120 function inDnsBlacklist( $ip, $base ) {
1121 wfProfileIn( __METHOD__ );
1122
1123 $found = false;
1124 $host = '';
1125 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1126 if( IP::isIPv4($ip) ) {
1127 # Make hostname
1128 $host = "$ip.$base";
1129
1130 # Send query
1131 $ipList = gethostbynamel( $host );
1132
1133 if( $ipList ) {
1134 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1135 $found = true;
1136 } else {
1137 wfDebug( "Requested $host, not found in $base.\n" );
1138 }
1139 }
1140
1141 wfProfileOut( __METHOD__ );
1142 return $found;
1143 }
1144
1145 /**
1146 * Is this user subject to rate limiting?
1147 *
1148 * @return \bool True if rate limited
1149 */
1150 public function isPingLimitable() {
1151 global $wgRateLimitsExcludedGroups;
1152 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1153 // Deprecated, but kept for backwards-compatibility config
1154 return false;
1155 }
1156 return !$this->isAllowed('noratelimit');
1157 }
1158
1159 /**
1160 * Primitive rate limits: enforce maximum actions per time period
1161 * to put a brake on flooding.
1162 *
1163 * @note When using a shared cache like memcached, IP-address
1164 * last-hit counters will be shared across wikis.
1165 *
1166 * @param $action \string Action to enforce; 'edit' if unspecified
1167 * @return \bool True if a rate limiter was tripped
1168 */
1169 function pingLimiter( $action='edit' ) {
1170
1171 # Call the 'PingLimiter' hook
1172 $result = false;
1173 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1174 return $result;
1175 }
1176
1177 global $wgRateLimits;
1178 if( !isset( $wgRateLimits[$action] ) ) {
1179 return false;
1180 }
1181
1182 # Some groups shouldn't trigger the ping limiter, ever
1183 if( !$this->isPingLimitable() )
1184 return false;
1185
1186 global $wgMemc, $wgRateLimitLog;
1187 wfProfileIn( __METHOD__ );
1188
1189 $limits = $wgRateLimits[$action];
1190 $keys = array();
1191 $id = $this->getId();
1192 $ip = wfGetIP();
1193 $userLimit = false;
1194
1195 if( isset( $limits['anon'] ) && $id == 0 ) {
1196 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1197 }
1198
1199 if( isset( $limits['user'] ) && $id != 0 ) {
1200 $userLimit = $limits['user'];
1201 }
1202 if( $this->isNewbie() ) {
1203 if( isset( $limits['newbie'] ) && $id != 0 ) {
1204 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1205 }
1206 if( isset( $limits['ip'] ) ) {
1207 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1208 }
1209 $matches = array();
1210 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1211 $subnet = $matches[1];
1212 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1213 }
1214 }
1215 // Check for group-specific permissions
1216 // If more than one group applies, use the group with the highest limit
1217 foreach ( $this->getGroups() as $group ) {
1218 if ( isset( $limits[$group] ) ) {
1219 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1220 $userLimit = $limits[$group];
1221 }
1222 }
1223 }
1224 // Set the user limit key
1225 if ( $userLimit !== false ) {
1226 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1227 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1228 }
1229
1230 $triggered = false;
1231 foreach( $keys as $key => $limit ) {
1232 list( $max, $period ) = $limit;
1233 $summary = "(limit $max in {$period}s)";
1234 $count = $wgMemc->get( $key );
1235 if( $count ) {
1236 if( $count > $max ) {
1237 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1238 if( $wgRateLimitLog ) {
1239 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1240 }
1241 $triggered = true;
1242 } else {
1243 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1244 }
1245 } else {
1246 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1247 $wgMemc->add( $key, 1, intval( $period ) );
1248 }
1249 $wgMemc->incr( $key );
1250 }
1251
1252 wfProfileOut( __METHOD__ );
1253 return $triggered;
1254 }
1255
1256 /**
1257 * Check if user is blocked
1258 *
1259 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1260 * @return \bool True if blocked, false otherwise
1261 */
1262 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1263 wfDebug( "User::isBlocked: enter\n" );
1264 $this->getBlockedStatus( $bFromSlave );
1265 return $this->mBlockedby !== 0;
1266 }
1267
1268 /**
1269 * Check if user is blocked from editing a particular article
1270 *
1271 * @param $title \string Title to check
1272 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1273 * @return \bool True if blocked, false otherwise
1274 */
1275 function isBlockedFrom( $title, $bFromSlave = false ) {
1276 global $wgBlockAllowsUTEdit;
1277 wfProfileIn( __METHOD__ );
1278 wfDebug( __METHOD__.": enter\n" );
1279
1280 wfDebug( __METHOD__.": asking isBlocked()\n" );
1281 $blocked = $this->isBlocked( $bFromSlave );
1282 $allowUsertalk = ($wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false);
1283 # If a user's name is suppressed, they cannot make edits anywhere
1284 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1285 $title->getNamespace() == NS_USER_TALK ) {
1286 $blocked = false;
1287 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1288 }
1289 wfProfileOut( __METHOD__ );
1290 return $blocked;
1291 }
1292
1293 /**
1294 * If user is blocked, return the name of the user who placed the block
1295 * @return \string name of blocker
1296 */
1297 function blockedBy() {
1298 $this->getBlockedStatus();
1299 return $this->mBlockedby;
1300 }
1301
1302 /**
1303 * If user is blocked, return the specified reason for the block
1304 * @return \string Blocking reason
1305 */
1306 function blockedFor() {
1307 $this->getBlockedStatus();
1308 return $this->mBlockreason;
1309 }
1310
1311 /**
1312 * Check if user is blocked on all wikis.
1313 * Do not use for actual edit permission checks!
1314 * This is intented for quick UI checks.
1315 *
1316 * @param $ip \type{\string} IP address, uses current client if none given
1317 * @return \type{\bool} True if blocked, false otherwise
1318 */
1319 function isBlockedGlobally( $ip = '' ) {
1320 if( $this->mBlockedGlobally !== null ) {
1321 return $this->mBlockedGlobally;
1322 }
1323 // User is already an IP?
1324 if( IP::isIPAddress( $this->getName() ) ) {
1325 $ip = $this->getName();
1326 } else if( !$ip ) {
1327 $ip = wfGetIP();
1328 }
1329 $blocked = false;
1330 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1331 $this->mBlockedGlobally = (bool)$blocked;
1332 return $this->mBlockedGlobally;
1333 }
1334
1335 /**
1336 * Check if user account is locked
1337 *
1338 * @return \type{\bool} True if locked, false otherwise
1339 */
1340 function isLocked() {
1341 if( $this->mLocked !== null ) {
1342 return $this->mLocked;
1343 }
1344 global $wgAuth;
1345 $authUser = $wgAuth->getUserInstance( $this );
1346 $this->mLocked = (bool)$authUser->isLocked();
1347 return $this->mLocked;
1348 }
1349
1350 /**
1351 * Check if user account is hidden
1352 *
1353 * @return \type{\bool} True if hidden, false otherwise
1354 */
1355 function isHidden() {
1356 if( $this->mHideName !== null ) {
1357 return $this->mHideName;
1358 }
1359 $this->getBlockedStatus();
1360 if( !$this->mHideName ) {
1361 global $wgAuth;
1362 $authUser = $wgAuth->getUserInstance( $this );
1363 $this->mHideName = (bool)$authUser->isHidden();
1364 }
1365 return $this->mHideName;
1366 }
1367
1368 /**
1369 * Get the user's ID.
1370 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1371 */
1372 function getId() {
1373 if( $this->mId === null and $this->mName !== null
1374 and User::isIP( $this->mName ) ) {
1375 // Special case, we know the user is anonymous
1376 return 0;
1377 } elseif( $this->mId === null ) {
1378 // Don't load if this was initialized from an ID
1379 $this->load();
1380 }
1381 return $this->mId;
1382 }
1383
1384 /**
1385 * Set the user and reload all fields according to a given ID
1386 * @param $v \int User ID to reload
1387 */
1388 function setId( $v ) {
1389 $this->mId = $v;
1390 $this->clearInstanceCache( 'id' );
1391 }
1392
1393 /**
1394 * Get the user name, or the IP of an anonymous user
1395 * @return \string User's name or IP address
1396 */
1397 function getName() {
1398 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1399 # Special case optimisation
1400 return $this->mName;
1401 } else {
1402 $this->load();
1403 if ( $this->mName === false ) {
1404 # Clean up IPs
1405 $this->mName = IP::sanitizeIP( wfGetIP() );
1406 }
1407 return $this->mName;
1408 }
1409 }
1410
1411 /**
1412 * Set the user name.
1413 *
1414 * This does not reload fields from the database according to the given
1415 * name. Rather, it is used to create a temporary "nonexistent user" for
1416 * later addition to the database. It can also be used to set the IP
1417 * address for an anonymous user to something other than the current
1418 * remote IP.
1419 *
1420 * @note User::newFromName() has rougly the same function, when the named user
1421 * does not exist.
1422 * @param $str \string New user name to set
1423 */
1424 function setName( $str ) {
1425 $this->load();
1426 $this->mName = $str;
1427 }
1428
1429 /**
1430 * Get the user's name escaped by underscores.
1431 * @return \string Username escaped by underscores.
1432 */
1433 function getTitleKey() {
1434 return str_replace( ' ', '_', $this->getName() );
1435 }
1436
1437 /**
1438 * Check if the user has new messages.
1439 * @return \bool True if the user has new messages
1440 */
1441 function getNewtalk() {
1442 $this->load();
1443
1444 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1445 if( $this->mNewtalk === -1 ) {
1446 $this->mNewtalk = false; # reset talk page status
1447
1448 # Check memcached separately for anons, who have no
1449 # entire User object stored in there.
1450 if( !$this->mId ) {
1451 global $wgMemc;
1452 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1453 $newtalk = $wgMemc->get( $key );
1454 if( strval( $newtalk ) !== '' ) {
1455 $this->mNewtalk = (bool)$newtalk;
1456 } else {
1457 // Since we are caching this, make sure it is up to date by getting it
1458 // from the master
1459 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1460 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1461 }
1462 } else {
1463 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1464 }
1465 }
1466
1467 return (bool)$this->mNewtalk;
1468 }
1469
1470 /**
1471 * Return the talk page(s) this user has new messages on.
1472 * @return \type{\arrayof{\string}} Array of page URLs
1473 */
1474 function getNewMessageLinks() {
1475 $talks = array();
1476 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1477 return $talks;
1478
1479 if (!$this->getNewtalk())
1480 return array();
1481 $up = $this->getUserPage();
1482 $utp = $up->getTalkPage();
1483 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1484 }
1485
1486
1487 /**
1488 * Internal uncached check for new messages
1489 *
1490 * @see getNewtalk()
1491 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1492 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1493 * @param $fromMaster \bool true to fetch from the master, false for a slave
1494 * @return \bool True if the user has new messages
1495 * @private
1496 */
1497 function checkNewtalk( $field, $id, $fromMaster = false ) {
1498 if ( $fromMaster ) {
1499 $db = wfGetDB( DB_MASTER );
1500 } else {
1501 $db = wfGetDB( DB_SLAVE );
1502 }
1503 $ok = $db->selectField( 'user_newtalk', $field,
1504 array( $field => $id ), __METHOD__ );
1505 return $ok !== false;
1506 }
1507
1508 /**
1509 * Add or update the new messages flag
1510 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1511 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1512 * @return \bool True if successful, false otherwise
1513 * @private
1514 */
1515 function updateNewtalk( $field, $id ) {
1516 $dbw = wfGetDB( DB_MASTER );
1517 $dbw->insert( 'user_newtalk',
1518 array( $field => $id ),
1519 __METHOD__,
1520 'IGNORE' );
1521 if ( $dbw->affectedRows() ) {
1522 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1523 return true;
1524 } else {
1525 wfDebug( __METHOD__." already set ($field, $id)\n" );
1526 return false;
1527 }
1528 }
1529
1530 /**
1531 * Clear the new messages flag for the given user
1532 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1533 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1534 * @return \bool True if successful, false otherwise
1535 * @private
1536 */
1537 function deleteNewtalk( $field, $id ) {
1538 $dbw = wfGetDB( DB_MASTER );
1539 $dbw->delete( 'user_newtalk',
1540 array( $field => $id ),
1541 __METHOD__ );
1542 if ( $dbw->affectedRows() ) {
1543 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1544 return true;
1545 } else {
1546 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1547 return false;
1548 }
1549 }
1550
1551 /**
1552 * Update the 'You have new messages!' status.
1553 * @param $val \bool Whether the user has new messages
1554 */
1555 function setNewtalk( $val ) {
1556 if( wfReadOnly() ) {
1557 return;
1558 }
1559
1560 $this->load();
1561 $this->mNewtalk = $val;
1562
1563 if( $this->isAnon() ) {
1564 $field = 'user_ip';
1565 $id = $this->getName();
1566 } else {
1567 $field = 'user_id';
1568 $id = $this->getId();
1569 }
1570 global $wgMemc;
1571
1572 if( $val ) {
1573 $changed = $this->updateNewtalk( $field, $id );
1574 } else {
1575 $changed = $this->deleteNewtalk( $field, $id );
1576 }
1577
1578 if( $this->isAnon() ) {
1579 // Anons have a separate memcached space, since
1580 // user records aren't kept for them.
1581 $key = wfMemcKey( 'newtalk', 'ip', $id );
1582 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1583 }
1584 if ( $changed ) {
1585 $this->invalidateCache();
1586 }
1587 }
1588
1589 /**
1590 * Generate a current or new-future timestamp to be stored in the
1591 * user_touched field when we update things.
1592 * @return \string Timestamp in TS_MW format
1593 */
1594 private static function newTouchedTimestamp() {
1595 global $wgClockSkewFudge;
1596 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1597 }
1598
1599 /**
1600 * Clear user data from memcached.
1601 * Use after applying fun updates to the database; caller's
1602 * responsibility to update user_touched if appropriate.
1603 *
1604 * Called implicitly from invalidateCache() and saveSettings().
1605 */
1606 private function clearSharedCache() {
1607 $this->load();
1608 if( $this->mId ) {
1609 global $wgMemc;
1610 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1611 }
1612 }
1613
1614 /**
1615 * Immediately touch the user data cache for this account.
1616 * Updates user_touched field, and removes account data from memcached
1617 * for reload on the next hit.
1618 */
1619 function invalidateCache() {
1620 $this->load();
1621 if( $this->mId ) {
1622 $this->mTouched = self::newTouchedTimestamp();
1623
1624 $dbw = wfGetDB( DB_MASTER );
1625 $dbw->update( 'user',
1626 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1627 array( 'user_id' => $this->mId ),
1628 __METHOD__ );
1629
1630 $this->clearSharedCache();
1631 }
1632 }
1633
1634 /**
1635 * Validate the cache for this account.
1636 * @param $timestamp \string A timestamp in TS_MW format
1637 */
1638 function validateCache( $timestamp ) {
1639 $this->load();
1640 return ($timestamp >= $this->mTouched);
1641 }
1642
1643 /**
1644 * Get the user touched timestamp
1645 */
1646 function getTouched() {
1647 $this->load();
1648 return $this->mTouched;
1649 }
1650
1651 /**
1652 * Set the password and reset the random token.
1653 * Calls through to authentication plugin if necessary;
1654 * will have no effect if the auth plugin refuses to
1655 * pass the change through or if the legal password
1656 * checks fail.
1657 *
1658 * As a special case, setting the password to null
1659 * wipes it, so the account cannot be logged in until
1660 * a new password is set, for instance via e-mail.
1661 *
1662 * @param $str \string New password to set
1663 * @throws PasswordError on failure
1664 */
1665 function setPassword( $str ) {
1666 global $wgAuth;
1667
1668 if( $str !== null ) {
1669 if( !$wgAuth->allowPasswordChange() ) {
1670 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1671 }
1672
1673 if( !$this->isValidPassword( $str ) ) {
1674 global $wgMinimalPasswordLength;
1675 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1676 $wgMinimalPasswordLength ) );
1677 }
1678 }
1679
1680 if( !$wgAuth->setPassword( $this, $str ) ) {
1681 throw new PasswordError( wfMsg( 'externaldberror' ) );
1682 }
1683
1684 $this->setInternalPassword( $str );
1685
1686 return true;
1687 }
1688
1689 /**
1690 * Set the password and reset the random token unconditionally.
1691 *
1692 * @param $str \string New password to set
1693 */
1694 function setInternalPassword( $str ) {
1695 $this->load();
1696 $this->setToken();
1697
1698 if( $str === null ) {
1699 // Save an invalid hash...
1700 $this->mPassword = '';
1701 } else {
1702 $this->mPassword = self::crypt( $str );
1703 }
1704 $this->mNewpassword = '';
1705 $this->mNewpassTime = null;
1706 }
1707
1708 /**
1709 * Get the user's current token.
1710 * @return \string Token
1711 */
1712 function getToken() {
1713 $this->load();
1714 return $this->mToken;
1715 }
1716
1717 /**
1718 * Set the random token (used for persistent authentication)
1719 * Called from loadDefaults() among other places.
1720 *
1721 * @param $token \string If specified, set the token to this value
1722 * @private
1723 */
1724 function setToken( $token = false ) {
1725 global $wgSecretKey, $wgProxyKey;
1726 $this->load();
1727 if ( !$token ) {
1728 if ( $wgSecretKey ) {
1729 $key = $wgSecretKey;
1730 } elseif ( $wgProxyKey ) {
1731 $key = $wgProxyKey;
1732 } else {
1733 $key = microtime();
1734 }
1735 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1736 } else {
1737 $this->mToken = $token;
1738 }
1739 }
1740
1741 /**
1742 * Set the cookie password
1743 *
1744 * @param $str \string New cookie password
1745 * @private
1746 */
1747 function setCookiePassword( $str ) {
1748 $this->load();
1749 $this->mCookiePassword = md5( $str );
1750 }
1751
1752 /**
1753 * Set the password for a password reminder or new account email
1754 *
1755 * @param $str \string New password to set
1756 * @param $throttle \bool If true, reset the throttle timestamp to the present
1757 */
1758 function setNewpassword( $str, $throttle = true ) {
1759 $this->load();
1760 $this->mNewpassword = self::crypt( $str );
1761 if ( $throttle ) {
1762 $this->mNewpassTime = wfTimestampNow();
1763 }
1764 }
1765
1766 /**
1767 * Has password reminder email been sent within the last
1768 * $wgPasswordReminderResendTime hours?
1769 * @return \bool True or false
1770 */
1771 function isPasswordReminderThrottled() {
1772 global $wgPasswordReminderResendTime;
1773 $this->load();
1774 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1775 return false;
1776 }
1777 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1778 return time() < $expiry;
1779 }
1780
1781 /**
1782 * Get the user's e-mail address
1783 * @return \string User's email address
1784 */
1785 function getEmail() {
1786 $this->load();
1787 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1788 return $this->mEmail;
1789 }
1790
1791 /**
1792 * Get the timestamp of the user's e-mail authentication
1793 * @return \string TS_MW timestamp
1794 */
1795 function getEmailAuthenticationTimestamp() {
1796 $this->load();
1797 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1798 return $this->mEmailAuthenticated;
1799 }
1800
1801 /**
1802 * Set the user's e-mail address
1803 * @param $str \string New e-mail address
1804 */
1805 function setEmail( $str ) {
1806 $this->load();
1807 $this->mEmail = $str;
1808 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1809 }
1810
1811 /**
1812 * Get the user's real name
1813 * @return \string User's real name
1814 */
1815 function getRealName() {
1816 $this->load();
1817 return $this->mRealName;
1818 }
1819
1820 /**
1821 * Set the user's real name
1822 * @param $str \string New real name
1823 */
1824 function setRealName( $str ) {
1825 $this->load();
1826 $this->mRealName = $str;
1827 }
1828
1829 /**
1830 * Get the user's current setting for a given option.
1831 *
1832 * @param $oname \string The option to check
1833 * @param $defaultOverride \string A default value returned if the option does not exist
1834 * @return \string User's current value for the option
1835 * @see getBoolOption()
1836 * @see getIntOption()
1837 */
1838 function getOption( $oname, $defaultOverride = '' ) {
1839 $this->load();
1840
1841 if ( is_null( $this->mOptions ) ) {
1842 if($defaultOverride != '') {
1843 return $defaultOverride;
1844 }
1845 $this->mOptions = User::getDefaultOptions();
1846 }
1847
1848 if ( array_key_exists( $oname, $this->mOptions ) ) {
1849 return trim( $this->mOptions[$oname] );
1850 } else {
1851 return $defaultOverride;
1852 }
1853 }
1854
1855 /**
1856 * Get the user's current setting for a given option, as a boolean value.
1857 *
1858 * @param $oname \string The option to check
1859 * @return \bool User's current value for the option
1860 * @see getOption()
1861 */
1862 function getBoolOption( $oname ) {
1863 return (bool)$this->getOption( $oname );
1864 }
1865
1866
1867 /**
1868 * Get the user's current setting for a given option, as a boolean value.
1869 *
1870 * @param $oname \string The option to check
1871 * @param $defaultOverride \int A default value returned if the option does not exist
1872 * @return \int User's current value for the option
1873 * @see getOption()
1874 */
1875 function getIntOption( $oname, $defaultOverride=0 ) {
1876 $val = $this->getOption( $oname );
1877 if( $val == '' ) {
1878 $val = $defaultOverride;
1879 }
1880 return intval( $val );
1881 }
1882
1883 /**
1884 * Set the given option for a user.
1885 *
1886 * @param $oname \string The option to set
1887 * @param $val \mixed New value to set
1888 */
1889 function setOption( $oname, $val ) {
1890 $this->load();
1891 if ( is_null( $this->mOptions ) ) {
1892 $this->mOptions = User::getDefaultOptions();
1893 }
1894 if ( $oname == 'skin' ) {
1895 # Clear cached skin, so the new one displays immediately in Special:Preferences
1896 unset( $this->mSkin );
1897 }
1898 // Filter out any newlines that may have passed through input validation.
1899 // Newlines are used to separate items in the options blob.
1900 if( $val ) {
1901 $val = str_replace( "\r\n", "\n", $val );
1902 $val = str_replace( "\r", "\n", $val );
1903 $val = str_replace( "\n", " ", $val );
1904 }
1905 // Explicitly NULL values should refer to defaults
1906 global $wgDefaultUserOptions;
1907 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1908 $val = $wgDefaultUserOptions[$oname];
1909 }
1910 $this->mOptions[$oname] = $val;
1911 }
1912
1913 /**
1914 * Get the user's preferred date format.
1915 * @return \string User's preferred date format
1916 */
1917 function getDatePreference() {
1918 // Important migration for old data rows
1919 if ( is_null( $this->mDatePreference ) ) {
1920 global $wgLang;
1921 $value = $this->getOption( 'date' );
1922 $map = $wgLang->getDatePreferenceMigrationMap();
1923 if ( isset( $map[$value] ) ) {
1924 $value = $map[$value];
1925 }
1926 $this->mDatePreference = $value;
1927 }
1928 return $this->mDatePreference;
1929 }
1930
1931 /**
1932 * Get the permissions this user has.
1933 * @return \type{\arrayof{\string}} Array of permission names
1934 */
1935 function getRights() {
1936 if ( is_null( $this->mRights ) ) {
1937 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1938 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1939 // Force reindexation of rights when a hook has unset one of them
1940 $this->mRights = array_values( $this->mRights );
1941 }
1942 return $this->mRights;
1943 }
1944
1945 /**
1946 * Get the list of explicit group memberships this user has.
1947 * The implicit * and user groups are not included.
1948 * @return \type{\arrayof{\string}} Array of internal group names
1949 */
1950 function getGroups() {
1951 $this->load();
1952 return $this->mGroups;
1953 }
1954
1955 /**
1956 * Get the list of implicit group memberships this user has.
1957 * This includes all explicit groups, plus 'user' if logged in,
1958 * '*' for all accounts and autopromoted groups
1959 * @param $recache \bool Whether to avoid the cache
1960 * @return \type{\arrayof{\string}} Array of internal group names
1961 */
1962 function getEffectiveGroups( $recache = false ) {
1963 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1964 $this->mEffectiveGroups = $this->getGroups();
1965 $this->mEffectiveGroups[] = '*';
1966 if( $this->getId() ) {
1967 $this->mEffectiveGroups[] = 'user';
1968
1969 $this->mEffectiveGroups = array_unique( array_merge(
1970 $this->mEffectiveGroups,
1971 Autopromote::getAutopromoteGroups( $this )
1972 ) );
1973
1974 # Hook for additional groups
1975 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1976 }
1977 }
1978 return $this->mEffectiveGroups;
1979 }
1980
1981 /**
1982 * Get the user's edit count.
1983 * @return \int User'e edit count
1984 */
1985 function getEditCount() {
1986 if ($this->mId) {
1987 if ( !isset( $this->mEditCount ) ) {
1988 /* Populate the count, if it has not been populated yet */
1989 $this->mEditCount = User::edits($this->mId);
1990 }
1991 return $this->mEditCount;
1992 } else {
1993 /* nil */
1994 return null;
1995 }
1996 }
1997
1998 /**
1999 * Add the user to the given group.
2000 * This takes immediate effect.
2001 * @param $group \string Name of the group to add
2002 */
2003 function addGroup( $group ) {
2004 $dbw = wfGetDB( DB_MASTER );
2005 if( $this->getId() ) {
2006 $dbw->insert( 'user_groups',
2007 array(
2008 'ug_user' => $this->getID(),
2009 'ug_group' => $group,
2010 ),
2011 'User::addGroup',
2012 array( 'IGNORE' ) );
2013 }
2014
2015 $this->loadGroups();
2016 $this->mGroups[] = $group;
2017 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2018
2019 $this->invalidateCache();
2020 }
2021
2022 /**
2023 * Remove the user from the given group.
2024 * This takes immediate effect.
2025 * @param $group \string Name of the group to remove
2026 */
2027 function removeGroup( $group ) {
2028 $this->load();
2029 $dbw = wfGetDB( DB_MASTER );
2030 $dbw->delete( 'user_groups',
2031 array(
2032 'ug_user' => $this->getID(),
2033 'ug_group' => $group,
2034 ),
2035 'User::removeGroup' );
2036
2037 $this->loadGroups();
2038 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2039 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2040
2041 $this->invalidateCache();
2042 }
2043
2044
2045 /**
2046 * Get whether the user is logged in
2047 * @return \bool True or false
2048 */
2049 function isLoggedIn() {
2050 return $this->getID() != 0;
2051 }
2052
2053 /**
2054 * Get whether the user is anonymous
2055 * @return \bool True or false
2056 */
2057 function isAnon() {
2058 return !$this->isLoggedIn();
2059 }
2060
2061 /**
2062 * Get whether the user is a bot
2063 * @return \bool True or false
2064 * @deprecated
2065 */
2066 function isBot() {
2067 wfDeprecated( __METHOD__ );
2068 return $this->isAllowed( 'bot' );
2069 }
2070
2071 /**
2072 * Check if user is allowed to access a feature / make an action
2073 * @param $action \string action to be checked
2074 * @return \bool True if action is allowed, else false
2075 */
2076 function isAllowed($action='') {
2077 if ( $action === '' )
2078 // In the spirit of DWIM
2079 return true;
2080
2081 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2082 # by misconfiguration: 0 == 'foo'
2083 return in_array( $action, $this->getRights(), true );
2084 }
2085
2086 /**
2087 * Check whether to enable recent changes patrol features for this user
2088 * @return \bool True or false
2089 */
2090 public function useRCPatrol() {
2091 global $wgUseRCPatrol;
2092 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2093 }
2094
2095 /**
2096 * Check whether to enable new pages patrol features for this user
2097 * @return \bool True or false
2098 */
2099 public function useNPPatrol() {
2100 global $wgUseRCPatrol, $wgUseNPPatrol;
2101 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2102 }
2103
2104 /**
2105 * Get the current skin, loading it if required
2106 * @return \type{Skin} Current skin
2107 * @todo FIXME : need to check the old failback system [AV]
2108 */
2109 function &getSkin() {
2110 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2111 if ( ! isset( $this->mSkin ) ) {
2112 wfProfileIn( __METHOD__ );
2113
2114 if( $wgAllowUserSkin ) {
2115 # get the user skin
2116 $userSkin = $this->getOption( 'skin' );
2117 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2118 } else {
2119 # if we're not allowing users to override, then use the default
2120 $userSkin = $wgDefaultSkin;
2121 }
2122
2123 $this->mSkin =& Skin::newFromKey( $userSkin );
2124 wfProfileOut( __METHOD__ );
2125 }
2126 return $this->mSkin;
2127 }
2128
2129 /**
2130 * Check the watched status of an article.
2131 * @param $title \type{Title} Title of the article to look at
2132 * @return \bool True if article is watched
2133 */
2134 function isWatched( $title ) {
2135 $wl = WatchedItem::fromUserTitle( $this, $title );
2136 return $wl->isWatched();
2137 }
2138
2139 /**
2140 * Watch an article.
2141 * @param $title \type{Title} Title of the article to look at
2142 */
2143 function addWatch( $title ) {
2144 $wl = WatchedItem::fromUserTitle( $this, $title );
2145 $wl->addWatch();
2146 $this->invalidateCache();
2147 }
2148
2149 /**
2150 * Stop watching an article.
2151 * @param $title \type{Title} Title of the article to look at
2152 */
2153 function removeWatch( $title ) {
2154 $wl = WatchedItem::fromUserTitle( $this, $title );
2155 $wl->removeWatch();
2156 $this->invalidateCache();
2157 }
2158
2159 /**
2160 * Clear the user's notification timestamp for the given title.
2161 * If e-notif e-mails are on, they will receive notification mails on
2162 * the next change of the page if it's watched etc.
2163 * @param $title \type{Title} Title of the article to look at
2164 */
2165 function clearNotification( &$title ) {
2166 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2167
2168 # Do nothing if the database is locked to writes
2169 if( wfReadOnly() ) {
2170 return;
2171 }
2172
2173 if ($title->getNamespace() == NS_USER_TALK &&
2174 $title->getText() == $this->getName() ) {
2175 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2176 return;
2177 $this->setNewtalk( false );
2178 }
2179
2180 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2181 return;
2182 }
2183
2184 if( $this->isAnon() ) {
2185 // Nothing else to do...
2186 return;
2187 }
2188
2189 // Only update the timestamp if the page is being watched.
2190 // The query to find out if it is watched is cached both in memcached and per-invocation,
2191 // and when it does have to be executed, it can be on a slave
2192 // If this is the user's newtalk page, we always update the timestamp
2193 if ($title->getNamespace() == NS_USER_TALK &&
2194 $title->getText() == $wgUser->getName())
2195 {
2196 $watched = true;
2197 } elseif ( $this->getId() == $wgUser->getId() ) {
2198 $watched = $title->userIsWatching();
2199 } else {
2200 $watched = true;
2201 }
2202
2203 // If the page is watched by the user (or may be watched), update the timestamp on any
2204 // any matching rows
2205 if ( $watched ) {
2206 $dbw = wfGetDB( DB_MASTER );
2207 $dbw->update( 'watchlist',
2208 array( /* SET */
2209 'wl_notificationtimestamp' => NULL
2210 ), array( /* WHERE */
2211 'wl_title' => $title->getDBkey(),
2212 'wl_namespace' => $title->getNamespace(),
2213 'wl_user' => $this->getID()
2214 ), __METHOD__
2215 );
2216 }
2217 }
2218
2219 /**
2220 * Resets all of the given user's page-change notification timestamps.
2221 * If e-notif e-mails are on, they will receive notification mails on
2222 * the next change of any watched page.
2223 *
2224 * @param $currentUser \int User ID
2225 */
2226 function clearAllNotifications( $currentUser ) {
2227 global $wgUseEnotif, $wgShowUpdatedMarker;
2228 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2229 $this->setNewtalk( false );
2230 return;
2231 }
2232 if( $currentUser != 0 ) {
2233 $dbw = wfGetDB( DB_MASTER );
2234 $dbw->update( 'watchlist',
2235 array( /* SET */
2236 'wl_notificationtimestamp' => NULL
2237 ), array( /* WHERE */
2238 'wl_user' => $currentUser
2239 ), __METHOD__
2240 );
2241 # We also need to clear here the "you have new message" notification for the own user_talk page
2242 # This is cleared one page view later in Article::viewUpdates();
2243 }
2244 }
2245
2246 /**
2247 * Encode this user's options as a string
2248 * @return \string Encoded options
2249 * @private
2250 */
2251 function encodeOptions() {
2252 $this->load();
2253 if ( is_null( $this->mOptions ) ) {
2254 $this->mOptions = User::getDefaultOptions();
2255 }
2256 $a = array();
2257 foreach ( $this->mOptions as $oname => $oval ) {
2258 array_push( $a, $oname.'='.$oval );
2259 }
2260 $s = implode( "\n", $a );
2261 return $s;
2262 }
2263
2264 /**
2265 * Set this user's options from an encoded string
2266 * @param $str \string Encoded options to import
2267 * @private
2268 */
2269 function decodeOptions( $str ) {
2270 $this->mOptions = array();
2271 $a = explode( "\n", $str );
2272 foreach ( $a as $s ) {
2273 $m = array();
2274 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2275 $this->mOptions[$m[1]] = $m[2];
2276 }
2277 }
2278 }
2279
2280 /**
2281 * Set a cookie on the user's client. Wrapper for
2282 * WebResponse::setCookie
2283 * @param $name \string Name of the cookie to set
2284 * @param $value \string Value to set
2285 * @param $exp \int Expiration time, as a UNIX time value;
2286 * if 0 or not specified, use the default $wgCookieExpiration
2287 */
2288 protected function setCookie( $name, $value, $exp=0 ) {
2289 global $wgRequest;
2290 $wgRequest->response()->setcookie( $name, $value, $exp );
2291 }
2292
2293 /**
2294 * Clear a cookie on the user's client
2295 * @param $name \string Name of the cookie to clear
2296 */
2297 protected function clearCookie( $name ) {
2298 $this->setCookie( $name, '', time() - 86400 );
2299 }
2300
2301 /**
2302 * Set the default cookies for this session on the user's client.
2303 */
2304 function setCookies() {
2305 $this->load();
2306 if ( 0 == $this->mId ) return;
2307 $session = array(
2308 'wsUserID' => $this->mId,
2309 'wsToken' => $this->mToken,
2310 'wsUserName' => $this->getName()
2311 );
2312 $cookies = array(
2313 'UserID' => $this->mId,
2314 'UserName' => $this->getName(),
2315 );
2316 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2317 $cookies['Token'] = $this->mToken;
2318 } else {
2319 $cookies['Token'] = false;
2320 }
2321
2322 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2323 #check for null, since the hook could cause a null value
2324 if ( !is_null( $session ) && !is_null( $_SESSION ) ){
2325 $_SESSION = $session + $_SESSION;
2326 }
2327 foreach ( $cookies as $name => $value ) {
2328 if ( $value === false ) {
2329 $this->clearCookie( $name );
2330 } else {
2331 $this->setCookie( $name, $value );
2332 }
2333 }
2334 }
2335
2336 /**
2337 * Log this user out.
2338 */
2339 function logout() {
2340 global $wgUser;
2341 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2342 $this->doLogout();
2343 }
2344 }
2345
2346 /**
2347 * Clear the user's cookies and session, and reset the instance cache.
2348 * @private
2349 * @see logout()
2350 */
2351 function doLogout() {
2352 $this->clearInstanceCache( 'defaults' );
2353
2354 $_SESSION['wsUserID'] = 0;
2355
2356 $this->clearCookie( 'UserID' );
2357 $this->clearCookie( 'Token' );
2358
2359 # Remember when user logged out, to prevent seeing cached pages
2360 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2361 }
2362
2363 /**
2364 * Save this user's settings into the database.
2365 * @todo Only rarely do all these fields need to be set!
2366 */
2367 function saveSettings() {
2368 $this->load();
2369 if ( wfReadOnly() ) { return; }
2370 if ( 0 == $this->mId ) { return; }
2371
2372 $this->mTouched = self::newTouchedTimestamp();
2373
2374 $dbw = wfGetDB( DB_MASTER );
2375 $dbw->update( 'user',
2376 array( /* SET */
2377 'user_name' => $this->mName,
2378 'user_password' => $this->mPassword,
2379 'user_newpassword' => $this->mNewpassword,
2380 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2381 'user_real_name' => $this->mRealName,
2382 'user_email' => $this->mEmail,
2383 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2384 'user_options' => $this->encodeOptions(),
2385 'user_touched' => $dbw->timestamp($this->mTouched),
2386 'user_token' => $this->mToken,
2387 'user_email_token' => $this->mEmailToken,
2388 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2389 ), array( /* WHERE */
2390 'user_id' => $this->mId
2391 ), __METHOD__
2392 );
2393 wfRunHooks( 'UserSaveSettings', array( $this ) );
2394 $this->clearSharedCache();
2395 $this->getUserPage()->invalidateCache();
2396 }
2397
2398 /**
2399 * If only this user's username is known, and it exists, return the user ID.
2400 */
2401 function idForName() {
2402 $s = trim( $this->getName() );
2403 if ( $s === '' ) return 0;
2404
2405 $dbr = wfGetDB( DB_SLAVE );
2406 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2407 if ( $id === false ) {
2408 $id = 0;
2409 }
2410 return $id;
2411 }
2412
2413 /**
2414 * Add a user to the database, return the user object
2415 *
2416 * @param $name \string Username to add
2417 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2418 * - password The user's password. Password logins will be disabled if this is omitted.
2419 * - newpassword A temporary password mailed to the user
2420 * - email The user's email address
2421 * - email_authenticated The email authentication timestamp
2422 * - real_name The user's real name
2423 * - options An associative array of non-default options
2424 * - token Random authentication token. Do not set.
2425 * - registration Registration timestamp. Do not set.
2426 *
2427 * @return \type{User} A new User object, or null if the username already exists
2428 */
2429 static function createNew( $name, $params = array() ) {
2430 $user = new User;
2431 $user->load();
2432 if ( isset( $params['options'] ) ) {
2433 $user->mOptions = $params['options'] + $user->mOptions;
2434 unset( $params['options'] );
2435 }
2436 $dbw = wfGetDB( DB_MASTER );
2437 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2438 $fields = array(
2439 'user_id' => $seqVal,
2440 'user_name' => $name,
2441 'user_password' => $user->mPassword,
2442 'user_newpassword' => $user->mNewpassword,
2443 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2444 'user_email' => $user->mEmail,
2445 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2446 'user_real_name' => $user->mRealName,
2447 'user_options' => $user->encodeOptions(),
2448 'user_token' => $user->mToken,
2449 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2450 'user_editcount' => 0,
2451 );
2452 foreach ( $params as $name => $value ) {
2453 $fields["user_$name"] = $value;
2454 }
2455 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2456 if ( $dbw->affectedRows() ) {
2457 $newUser = User::newFromId( $dbw->insertId() );
2458 } else {
2459 $newUser = null;
2460 }
2461 return $newUser;
2462 }
2463
2464 /**
2465 * Add this existing user object to the database
2466 */
2467 function addToDatabase() {
2468 $this->load();
2469 $dbw = wfGetDB( DB_MASTER );
2470 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2471 $dbw->insert( 'user',
2472 array(
2473 'user_id' => $seqVal,
2474 'user_name' => $this->mName,
2475 'user_password' => $this->mPassword,
2476 'user_newpassword' => $this->mNewpassword,
2477 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2478 'user_email' => $this->mEmail,
2479 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2480 'user_real_name' => $this->mRealName,
2481 'user_options' => $this->encodeOptions(),
2482 'user_token' => $this->mToken,
2483 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2484 'user_editcount' => 0,
2485 ), __METHOD__
2486 );
2487 $this->mId = $dbw->insertId();
2488
2489 // Clear instance cache other than user table data, which is already accurate
2490 $this->clearInstanceCache();
2491 }
2492
2493 /**
2494 * If this (non-anonymous) user is blocked, block any IP address
2495 * they've successfully logged in from.
2496 */
2497 function spreadBlock() {
2498 wfDebug( __METHOD__."()\n" );
2499 $this->load();
2500 if ( $this->mId == 0 ) {
2501 return;
2502 }
2503
2504 $userblock = Block::newFromDB( '', $this->mId );
2505 if ( !$userblock ) {
2506 return;
2507 }
2508
2509 $userblock->doAutoblock( wfGetIp() );
2510
2511 }
2512
2513 /**
2514 * Generate a string which will be different for any combination of
2515 * user options which would produce different parser output.
2516 * This will be used as part of the hash key for the parser cache,
2517 * so users will the same options can share the same cached data
2518 * safely.
2519 *
2520 * Extensions which require it should install 'PageRenderingHash' hook,
2521 * which will give them a chance to modify this key based on their own
2522 * settings.
2523 *
2524 * @return \string Page rendering hash
2525 */
2526 function getPageRenderingHash() {
2527 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2528 if( $this->mHash ){
2529 return $this->mHash;
2530 }
2531
2532 // stubthreshold is only included below for completeness,
2533 // it will always be 0 when this function is called by parsercache.
2534
2535 $confstr = $this->getOption( 'math' );
2536 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2537 if ( $wgUseDynamicDates ) {
2538 $confstr .= '!' . $this->getDatePreference();
2539 }
2540 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2541 $confstr .= '!' . $wgLang->getCode();
2542 $confstr .= '!' . $this->getOption( 'thumbsize' );
2543 // add in language specific options, if any
2544 $extra = $wgContLang->getExtraHashOptions();
2545 $confstr .= $extra;
2546
2547 $confstr .= $wgRenderHashAppend;
2548
2549 // Give a chance for extensions to modify the hash, if they have
2550 // extra options or other effects on the parser cache.
2551 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2552
2553 // Make it a valid memcached key fragment
2554 $confstr = str_replace( ' ', '_', $confstr );
2555 $this->mHash = $confstr;
2556 return $confstr;
2557 }
2558
2559 /**
2560 * Get whether the user is explicitly blocked from account creation.
2561 * @return \bool True if blocked
2562 */
2563 function isBlockedFromCreateAccount() {
2564 $this->getBlockedStatus();
2565 return $this->mBlock && $this->mBlock->mCreateAccount;
2566 }
2567
2568 /**
2569 * Get whether the user is blocked from using Special:Emailuser.
2570 * @return \bool True if blocked
2571 */
2572 function isBlockedFromEmailuser() {
2573 $this->getBlockedStatus();
2574 return $this->mBlock && $this->mBlock->mBlockEmail;
2575 }
2576
2577 /**
2578 * Get whether the user is allowed to create an account.
2579 * @return \bool True if allowed
2580 */
2581 function isAllowedToCreateAccount() {
2582 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2583 }
2584
2585 /**
2586 * @deprecated
2587 */
2588 function setLoaded( $loaded ) {
2589 wfDeprecated( __METHOD__ );
2590 }
2591
2592 /**
2593 * Get this user's personal page title.
2594 *
2595 * @return \type{Title} User's personal page title
2596 */
2597 function getUserPage() {
2598 return Title::makeTitle( NS_USER, $this->getName() );
2599 }
2600
2601 /**
2602 * Get this user's talk page title.
2603 *
2604 * @return \type{Title} User's talk page title
2605 */
2606 function getTalkPage() {
2607 $title = $this->getUserPage();
2608 return $title->getTalkPage();
2609 }
2610
2611 /**
2612 * Get the maximum valid user ID.
2613 * @return \int User ID
2614 * @static
2615 */
2616 function getMaxID() {
2617 static $res; // cache
2618
2619 if ( isset( $res ) )
2620 return $res;
2621 else {
2622 $dbr = wfGetDB( DB_SLAVE );
2623 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2624 }
2625 }
2626
2627 /**
2628 * Determine whether the user is a newbie. Newbies are either
2629 * anonymous IPs, or the most recently created accounts.
2630 * @return \bool True if the user is a newbie
2631 */
2632 function isNewbie() {
2633 return !$this->isAllowed( 'autoconfirmed' );
2634 }
2635
2636 /**
2637 * Is the user active? We check to see if they've made at least
2638 * X number of edits in the last Y days.
2639 *
2640 * @return \bool True if the user is active, false if not.
2641 */
2642 public function isActiveEditor() {
2643 global $wgActiveUserEditCount, $wgActiveUserDays;
2644 $dbr = wfGetDB( DB_SLAVE );
2645
2646 // Stolen without shame from RC
2647 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2648 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2649 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2650
2651 $res = $dbr->select( 'revision', '1',
2652 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2653 __METHOD__,
2654 array('LIMIT' => $wgActiveUserEditCount ) );
2655
2656 $count = $dbr->numRows($res);
2657 $dbr->freeResult($res);
2658
2659 return $count == $wgActiveUserEditCount;
2660 }
2661
2662 /**
2663 * Check to see if the given clear-text password is one of the accepted passwords
2664 * @param $password \string user password.
2665 * @return \bool True if the given password is correct, otherwise False.
2666 */
2667 function checkPassword( $password ) {
2668 global $wgAuth;
2669 $this->load();
2670
2671 // Even though we stop people from creating passwords that
2672 // are shorter than this, doesn't mean people wont be able
2673 // to. Certain authentication plugins do NOT want to save
2674 // domain passwords in a mysql database, so we should
2675 // check this (incase $wgAuth->strict() is false).
2676 if( !$this->isValidPassword( $password ) ) {
2677 return false;
2678 }
2679
2680 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2681 return true;
2682 } elseif( $wgAuth->strict() ) {
2683 /* Auth plugin doesn't allow local authentication */
2684 return false;
2685 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2686 /* Auth plugin doesn't allow local authentication for this user name */
2687 return false;
2688 }
2689 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2690 return true;
2691 } elseif ( function_exists( 'iconv' ) ) {
2692 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2693 # Check for this with iconv
2694 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2695 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2696 return true;
2697 }
2698 }
2699 return false;
2700 }
2701
2702 /**
2703 * Check if the given clear-text password matches the temporary password
2704 * sent by e-mail for password reset operations.
2705 * @return \bool True if matches, false otherwise
2706 */
2707 function checkTemporaryPassword( $plaintext ) {
2708 return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() );
2709 }
2710
2711 /**
2712 * Initialize (if necessary) and return a session token value
2713 * which can be used in edit forms to show that the user's
2714 * login credentials aren't being hijacked with a foreign form
2715 * submission.
2716 *
2717 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2718 * @return \string The new edit token
2719 */
2720 function editToken( $salt = '' ) {
2721 if ( $this->isAnon() ) {
2722 return EDIT_TOKEN_SUFFIX;
2723 } else {
2724 if( !isset( $_SESSION['wsEditToken'] ) ) {
2725 $token = $this->generateToken();
2726 $_SESSION['wsEditToken'] = $token;
2727 } else {
2728 $token = $_SESSION['wsEditToken'];
2729 }
2730 if( is_array( $salt ) ) {
2731 $salt = implode( '|', $salt );
2732 }
2733 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2734 }
2735 }
2736
2737 /**
2738 * Generate a looking random token for various uses.
2739 *
2740 * @param $salt \string Optional salt value
2741 * @return \string The new random token
2742 */
2743 function generateToken( $salt = '' ) {
2744 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2745 return md5( $token . $salt );
2746 }
2747
2748 /**
2749 * Check given value against the token value stored in the session.
2750 * A match should confirm that the form was submitted from the
2751 * user's own login session, not a form submission from a third-party
2752 * site.
2753 *
2754 * @param $val \string Input value to compare
2755 * @param $salt \string Optional function-specific data for hashing
2756 * @return \bool Whether the token matches
2757 */
2758 function matchEditToken( $val, $salt = '' ) {
2759 $sessionToken = $this->editToken( $salt );
2760 if ( $val != $sessionToken ) {
2761 wfDebug( "User::matchEditToken: broken session data\n" );
2762 }
2763 return $val == $sessionToken;
2764 }
2765
2766 /**
2767 * Check given value against the token value stored in the session,
2768 * ignoring the suffix.
2769 *
2770 * @param $val \string Input value to compare
2771 * @param $salt \string Optional function-specific data for hashing
2772 * @return \bool Whether the token matches
2773 */
2774 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2775 $sessionToken = $this->editToken( $salt );
2776 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2777 }
2778
2779 /**
2780 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2781 * mail to the user's given address.
2782 *
2783 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2784 */
2785 function sendConfirmationMail() {
2786 global $wgLang;
2787 $expiration = null; // gets passed-by-ref and defined in next line.
2788 $token = $this->confirmationToken( $expiration );
2789 $url = $this->confirmationTokenUrl( $token );
2790 $invalidateURL = $this->invalidationTokenUrl( $token );
2791 $this->saveSettings();
2792
2793 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2794 wfMsg( 'confirmemail_body',
2795 wfGetIP(),
2796 $this->getName(),
2797 $url,
2798 $wgLang->timeanddate( $expiration, false ),
2799 $invalidateURL ) );
2800 }
2801
2802 /**
2803 * Send an e-mail to this user's account. Does not check for
2804 * confirmed status or validity.
2805 *
2806 * @param $subject \string Message subject
2807 * @param $body \string Message body
2808 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2809 * @param $replyto \string Reply-To address
2810 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2811 */
2812 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2813 if( is_null( $from ) ) {
2814 global $wgPasswordSender;
2815 $from = $wgPasswordSender;
2816 }
2817
2818 $to = new MailAddress( $this );
2819 $sender = new MailAddress( $from );
2820 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2821 }
2822
2823 /**
2824 * Generate, store, and return a new e-mail confirmation code.
2825 * A hash (unsalted, since it's used as a key) is stored.
2826 *
2827 * @note Call saveSettings() after calling this function to commit
2828 * this change to the database.
2829 *
2830 * @param[out] &$expiration \mixed Accepts the expiration time
2831 * @return \string New token
2832 * @private
2833 */
2834 function confirmationToken( &$expiration ) {
2835 $now = time();
2836 $expires = $now + 7 * 24 * 60 * 60;
2837 $expiration = wfTimestamp( TS_MW, $expires );
2838 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2839 $hash = md5( $token );
2840 $this->load();
2841 $this->mEmailToken = $hash;
2842 $this->mEmailTokenExpires = $expiration;
2843 return $token;
2844 }
2845
2846 /**
2847 * Return a URL the user can use to confirm their email address.
2848 * @param $token \string Accepts the email confirmation token
2849 * @return \string New token URL
2850 * @private
2851 */
2852 function confirmationTokenUrl( $token ) {
2853 return $this->getTokenUrl( 'ConfirmEmail', $token );
2854 }
2855 /**
2856 * Return a URL the user can use to invalidate their email address.
2857 * @param $token \string Accepts the email confirmation token
2858 * @return \string New token URL
2859 * @private
2860 */
2861 function invalidationTokenUrl( $token ) {
2862 return $this->getTokenUrl( 'Invalidateemail', $token );
2863 }
2864
2865 /**
2866 * Internal function to format the e-mail validation/invalidation URLs.
2867 * This uses $wgArticlePath directly as a quickie hack to use the
2868 * hardcoded English names of the Special: pages, for ASCII safety.
2869 *
2870 * @note Since these URLs get dropped directly into emails, using the
2871 * short English names avoids insanely long URL-encoded links, which
2872 * also sometimes can get corrupted in some browsers/mailers
2873 * (bug 6957 with Gmail and Internet Explorer).
2874 *
2875 * @param $page \string Special page
2876 * @param $token \string Token
2877 * @return \string Formatted URL
2878 */
2879 protected function getTokenUrl( $page, $token ) {
2880 global $wgArticlePath;
2881 return wfExpandUrl(
2882 str_replace(
2883 '$1',
2884 "Special:$page/$token",
2885 $wgArticlePath ) );
2886 }
2887
2888 /**
2889 * Mark the e-mail address confirmed.
2890 *
2891 * @note Call saveSettings() after calling this function to commit the change.
2892 */
2893 function confirmEmail() {
2894 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2895 return true;
2896 }
2897
2898 /**
2899 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2900 * address if it was already confirmed.
2901 *
2902 * @note Call saveSettings() after calling this function to commit the change.
2903 */
2904 function invalidateEmail() {
2905 $this->load();
2906 $this->mEmailToken = null;
2907 $this->mEmailTokenExpires = null;
2908 $this->setEmailAuthenticationTimestamp( null );
2909 return true;
2910 }
2911
2912 /**
2913 * Set the e-mail authentication timestamp.
2914 * @param $timestamp \string TS_MW timestamp
2915 */
2916 function setEmailAuthenticationTimestamp( $timestamp ) {
2917 $this->load();
2918 $this->mEmailAuthenticated = $timestamp;
2919 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2920 }
2921
2922 /**
2923 * Is this user allowed to send e-mails within limits of current
2924 * site configuration?
2925 * @return \bool True if allowed
2926 */
2927 function canSendEmail() {
2928 global $wgEnableEmail, $wgEnableUserEmail;
2929 if( !$wgEnableEmail || !$wgEnableUserEmail ) {
2930 return false;
2931 }
2932 $canSend = $this->isEmailConfirmed();
2933 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2934 return $canSend;
2935 }
2936
2937 /**
2938 * Is this user allowed to receive e-mails within limits of current
2939 * site configuration?
2940 * @return \bool True if allowed
2941 */
2942 function canReceiveEmail() {
2943 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2944 }
2945
2946 /**
2947 * Is this user's e-mail address valid-looking and confirmed within
2948 * limits of the current site configuration?
2949 *
2950 * @note If $wgEmailAuthentication is on, this may require the user to have
2951 * confirmed their address by returning a code or using a password
2952 * sent to the address from the wiki.
2953 *
2954 * @return \bool True if confirmed
2955 */
2956 function isEmailConfirmed() {
2957 global $wgEmailAuthentication;
2958 $this->load();
2959 $confirmed = true;
2960 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2961 if( $this->isAnon() )
2962 return false;
2963 if( !self::isValidEmailAddr( $this->mEmail ) )
2964 return false;
2965 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2966 return false;
2967 return true;
2968 } else {
2969 return $confirmed;
2970 }
2971 }
2972
2973 /**
2974 * Check whether there is an outstanding request for e-mail confirmation.
2975 * @return \bool True if pending
2976 */
2977 function isEmailConfirmationPending() {
2978 global $wgEmailAuthentication;
2979 return $wgEmailAuthentication &&
2980 !$this->isEmailConfirmed() &&
2981 $this->mEmailToken &&
2982 $this->mEmailTokenExpires > wfTimestamp();
2983 }
2984
2985 /**
2986 * Get the timestamp of account creation.
2987 *
2988 * @return \types{\string,\bool} string Timestamp of account creation, or false for
2989 * non-existent/anonymous user accounts.
2990 */
2991 public function getRegistration() {
2992 return $this->mId > 0
2993 ? $this->mRegistration
2994 : false;
2995 }
2996
2997 /**
2998 * Get the permissions associated with a given list of groups
2999 *
3000 * @param $groups \type{\arrayof{\string}} List of internal group names
3001 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3002 */
3003 static function getGroupPermissions( $groups ) {
3004 global $wgGroupPermissions;
3005 $rights = array();
3006 foreach( $groups as $group ) {
3007 if( isset( $wgGroupPermissions[$group] ) ) {
3008 $rights = array_merge( $rights,
3009 // array_filter removes empty items
3010 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3011 }
3012 }
3013 return array_unique($rights);
3014 }
3015
3016 /**
3017 * Get all the groups who have a given permission
3018 *
3019 * @param $role \string Role to check
3020 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3021 */
3022 static function getGroupsWithPermission( $role ) {
3023 global $wgGroupPermissions;
3024 $allowedGroups = array();
3025 foreach ( $wgGroupPermissions as $group => $rights ) {
3026 if ( isset( $rights[$role] ) && $rights[$role] ) {
3027 $allowedGroups[] = $group;
3028 }
3029 }
3030 return $allowedGroups;
3031 }
3032
3033 /**
3034 * Get the localized descriptive name for a group, if it exists
3035 *
3036 * @param $group \string Internal group name
3037 * @return \string Localized descriptive group name
3038 */
3039 static function getGroupName( $group ) {
3040 global $wgMessageCache;
3041 $wgMessageCache->loadAllMessages();
3042 $key = "group-$group";
3043 $name = wfMsg( $key );
3044 return $name == '' || wfEmptyMsg( $key, $name )
3045 ? $group
3046 : $name;
3047 }
3048
3049 /**
3050 * Get the localized descriptive name for a member of a group, if it exists
3051 *
3052 * @param $group \string Internal group name
3053 * @return \string Localized name for group member
3054 */
3055 static function getGroupMember( $group ) {
3056 global $wgMessageCache;
3057 $wgMessageCache->loadAllMessages();
3058 $key = "group-$group-member";
3059 $name = wfMsg( $key );
3060 return $name == '' || wfEmptyMsg( $key, $name )
3061 ? $group
3062 : $name;
3063 }
3064
3065 /**
3066 * Return the set of defined explicit groups.
3067 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3068 * are not included, as they are defined automatically, not in the database.
3069 * @return \type{\arrayof{\string}} Array of internal group names
3070 */
3071 static function getAllGroups() {
3072 global $wgGroupPermissions;
3073 return array_diff(
3074 array_keys( $wgGroupPermissions ),
3075 self::getImplicitGroups()
3076 );
3077 }
3078
3079 /**
3080 * Get a list of all available permissions.
3081 * @return \type{\arrayof{\string}} Array of permission names
3082 */
3083 static function getAllRights() {
3084 if ( self::$mAllRights === false ) {
3085 global $wgAvailableRights;
3086 if ( count( $wgAvailableRights ) ) {
3087 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3088 } else {
3089 self::$mAllRights = self::$mCoreRights;
3090 }
3091 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3092 }
3093 return self::$mAllRights;
3094 }
3095
3096 /**
3097 * Get a list of implicit groups
3098 * @return \type{\arrayof{\string}} Array of internal group names
3099 */
3100 public static function getImplicitGroups() {
3101 global $wgImplicitGroups;
3102 $groups = $wgImplicitGroups;
3103 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3104 return $groups;
3105 }
3106
3107 /**
3108 * Get the title of a page describing a particular group
3109 *
3110 * @param $group \string Internal group name
3111 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3112 */
3113 static function getGroupPage( $group ) {
3114 global $wgMessageCache;
3115 $wgMessageCache->loadAllMessages();
3116 $page = wfMsgForContent( 'grouppage-' . $group );
3117 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3118 $title = Title::newFromText( $page );
3119 if( is_object( $title ) )
3120 return $title;
3121 }
3122 return false;
3123 }
3124
3125 /**
3126 * Create a link to the group in HTML, if available;
3127 * else return the group name.
3128 *
3129 * @param $group \string Internal name of the group
3130 * @param $text \string The text of the link
3131 * @return \string HTML link to the group
3132 */
3133 static function makeGroupLinkHTML( $group, $text = '' ) {
3134 if( $text == '' ) {
3135 $text = self::getGroupName( $group );
3136 }
3137 $title = self::getGroupPage( $group );
3138 if( $title ) {
3139 global $wgUser;
3140 $sk = $wgUser->getSkin();
3141 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3142 } else {
3143 return $text;
3144 }
3145 }
3146
3147 /**
3148 * Create a link to the group in Wikitext, if available;
3149 * else return the group name.
3150 *
3151 * @param $group \string Internal name of the group
3152 * @param $text \string The text of the link
3153 * @return \string Wikilink to the group
3154 */
3155 static function makeGroupLinkWiki( $group, $text = '' ) {
3156 if( $text == '' ) {
3157 $text = self::getGroupName( $group );
3158 }
3159 $title = self::getGroupPage( $group );
3160 if( $title ) {
3161 $page = $title->getPrefixedText();
3162 return "[[$page|$text]]";
3163 } else {
3164 return $text;
3165 }
3166 }
3167
3168 /**
3169 * Increment the user's edit-count field.
3170 * Will have no effect for anonymous users.
3171 */
3172 function incEditCount() {
3173 if( !$this->isAnon() ) {
3174 $dbw = wfGetDB( DB_MASTER );
3175 $dbw->update( 'user',
3176 array( 'user_editcount=user_editcount+1' ),
3177 array( 'user_id' => $this->getId() ),
3178 __METHOD__ );
3179
3180 // Lazy initialization check...
3181 if( $dbw->affectedRows() == 0 ) {
3182 // Pull from a slave to be less cruel to servers
3183 // Accuracy isn't the point anyway here
3184 $dbr = wfGetDB( DB_SLAVE );
3185 $count = $dbr->selectField( 'revision',
3186 'COUNT(rev_user)',
3187 array( 'rev_user' => $this->getId() ),
3188 __METHOD__ );
3189
3190 // Now here's a goddamn hack...
3191 if( $dbr !== $dbw ) {
3192 // If we actually have a slave server, the count is
3193 // at least one behind because the current transaction
3194 // has not been committed and replicated.
3195 $count++;
3196 } else {
3197 // But if DB_SLAVE is selecting the master, then the
3198 // count we just read includes the revision that was
3199 // just added in the working transaction.
3200 }
3201
3202 $dbw->update( 'user',
3203 array( 'user_editcount' => $count ),
3204 array( 'user_id' => $this->getId() ),
3205 __METHOD__ );
3206 }
3207 }
3208 // edit count in user cache too
3209 $this->invalidateCache();
3210 }
3211
3212 /**
3213 * Get the description of a given right
3214 *
3215 * @param $right \string Right to query
3216 * @return \string Localized description of the right
3217 */
3218 static function getRightDescription( $right ) {
3219 global $wgMessageCache;
3220 $wgMessageCache->loadAllMessages();
3221 $key = "right-$right";
3222 $name = wfMsg( $key );
3223 return $name == '' || wfEmptyMsg( $key, $name )
3224 ? $right
3225 : $name;
3226 }
3227
3228 /**
3229 * Make an old-style password hash
3230 *
3231 * @param $password \string Plain-text password
3232 * @param $userId \string User ID
3233 * @return \string Password hash
3234 */
3235 static function oldCrypt( $password, $userId ) {
3236 global $wgPasswordSalt;
3237 if ( $wgPasswordSalt ) {
3238 return md5( $userId . '-' . md5( $password ) );
3239 } else {
3240 return md5( $password );
3241 }
3242 }
3243
3244 /**
3245 * Make a new-style password hash
3246 *
3247 * @param $password \string Plain-text password
3248 * @param $salt \string Optional salt, may be random or the user ID.
3249 * If unspecified or false, will generate one automatically
3250 * @return \string Password hash
3251 */
3252 static function crypt( $password, $salt = false ) {
3253 global $wgPasswordSalt;
3254
3255 $hash = '';
3256 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3257 return $hash;
3258 }
3259
3260 if( $wgPasswordSalt ) {
3261 if ( $salt === false ) {
3262 $salt = substr( wfGenerateToken(), 0, 8 );
3263 }
3264 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3265 } else {
3266 return ':A:' . md5( $password );
3267 }
3268 }
3269
3270 /**
3271 * Compare a password hash with a plain-text password. Requires the user
3272 * ID if there's a chance that the hash is an old-style hash.
3273 *
3274 * @param $hash \string Password hash
3275 * @param $password \string Plain-text password to compare
3276 * @param $userId \string User ID for old-style password salt
3277 * @return \bool
3278 */
3279 static function comparePasswords( $hash, $password, $userId = false ) {
3280 $m = false;
3281 $type = substr( $hash, 0, 3 );
3282
3283 $result = false;
3284 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3285 return $result;
3286 }
3287
3288 if ( $type == ':A:' ) {
3289 # Unsalted
3290 return md5( $password ) === substr( $hash, 3 );
3291 } elseif ( $type == ':B:' ) {
3292 # Salted
3293 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3294 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3295 } else {
3296 # Old-style
3297 return self::oldCrypt( $password, $userId ) === $hash;
3298 }
3299 }
3300
3301 /**
3302 * Add a newuser log entry for this user
3303 * @param $byEmail Boolean: account made by email?
3304 */
3305 public function addNewUserLogEntry( $byEmail = false ) {
3306 global $wgUser, $wgContLang, $wgNewUserLog;
3307 if( empty($wgNewUserLog) ) {
3308 return true; // disabled
3309 }
3310 $talk = $wgContLang->getFormattedNsText( NS_TALK );
3311 if( $this->getName() == $wgUser->getName() ) {
3312 $action = 'create';
3313 $message = '';
3314 } else {
3315 $action = 'create2';
3316 $message = $byEmail ? wfMsgForContent( 'newuserlog-byemail' ) : '';
3317 }
3318 $log = new LogPage( 'newusers' );
3319 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3320 return true;
3321 }
3322
3323 /**
3324 * Add an autocreate newuser log entry for this user
3325 * Used by things like CentralAuth and perhaps other authplugins.
3326 */
3327 public function addNewUserLogEntryAutoCreate() {
3328 global $wgNewUserLog;
3329 if( empty($wgNewUserLog) ) {
3330 return true; // disabled
3331 }
3332 $log = new LogPage( 'newusers', false );
3333 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3334 return true;
3335 }
3336
3337 }