isAllowed('patrol') now returns false if patrolling is disabled
[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 'ipblock-exempt',
150 'markbotedits',
151 'minoredit',
152 'move',
153 'movefile',
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 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
890
891 if ( $s !== false ) {
892 # Initialise user table data
893 $this->loadFromRow( $s );
894 $this->mGroups = null; // deferred
895 $this->getEditCount(); // revalidation for nulls
896 return true;
897 } else {
898 # Invalid user_id
899 $this->mId = 0;
900 $this->loadDefaults();
901 return false;
902 }
903 }
904
905 /**
906 * Initialize this object from a row from the user table.
907 *
908 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
909 */
910 function loadFromRow( $row ) {
911 $this->mDataLoaded = true;
912
913 if ( isset( $row->user_id ) ) {
914 $this->mId = $row->user_id;
915 }
916 $this->mName = $row->user_name;
917 $this->mRealName = $row->user_real_name;
918 $this->mPassword = $row->user_password;
919 $this->mNewpassword = $row->user_newpassword;
920 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
921 $this->mEmail = $row->user_email;
922 $this->decodeOptions( $row->user_options );
923 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
924 $this->mToken = $row->user_token;
925 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
926 $this->mEmailToken = $row->user_email_token;
927 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
928 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
929 $this->mEditCount = $row->user_editcount;
930 }
931
932 /**
933 * Load the groups from the database if they aren't already loaded.
934 * @private
935 */
936 function loadGroups() {
937 if ( is_null( $this->mGroups ) ) {
938 $dbr = wfGetDB( DB_MASTER );
939 $res = $dbr->select( 'user_groups',
940 array( 'ug_group' ),
941 array( 'ug_user' => $this->mId ),
942 __METHOD__ );
943 $this->mGroups = array();
944 while( $row = $dbr->fetchObject( $res ) ) {
945 $this->mGroups[] = $row->ug_group;
946 }
947 }
948 }
949
950 /**
951 * Clear various cached data stored in this object.
952 * @param $reloadFrom \string Reload user and user_groups table data from a
953 * given source. May be "name", "id", "defaults", "session", or false for
954 * no reload.
955 */
956 function clearInstanceCache( $reloadFrom = false ) {
957 $this->mNewtalk = -1;
958 $this->mDatePreference = null;
959 $this->mBlockedby = -1; # Unset
960 $this->mHash = false;
961 $this->mSkin = null;
962 $this->mRights = null;
963 $this->mEffectiveGroups = null;
964
965 if ( $reloadFrom ) {
966 $this->mDataLoaded = false;
967 $this->mFrom = $reloadFrom;
968 }
969 }
970
971 /**
972 * Combine the language default options with any site-specific options
973 * and add the default language variants.
974 *
975 * @return \type{\arrayof{\string}} Array of options
976 */
977 static function getDefaultOptions() {
978 global $wgNamespacesToBeSearchedDefault;
979 /**
980 * Site defaults will override the global/language defaults
981 */
982 global $wgDefaultUserOptions, $wgContLang;
983 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
984
985 /**
986 * default language setting
987 */
988 $variant = $wgContLang->getPreferredVariant( false );
989 $defOpt['variant'] = $variant;
990 $defOpt['language'] = $variant;
991
992 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
993 $defOpt['searchNs'.$nsnum] = $val;
994 }
995 return $defOpt;
996 }
997
998 /**
999 * Get a given default option value.
1000 *
1001 * @param $opt \string Name of option to retrieve
1002 * @return \string Default option value
1003 */
1004 public static function getDefaultOption( $opt ) {
1005 $defOpts = self::getDefaultOptions();
1006 if( isset( $defOpts[$opt] ) ) {
1007 return $defOpts[$opt];
1008 } else {
1009 return '';
1010 }
1011 }
1012
1013 /**
1014 * Get a list of user toggle names
1015 * @return \type{\arrayof{\string}} Array of user toggle names
1016 */
1017 static function getToggles() {
1018 global $wgContLang, $wgUseRCPatrol;
1019 $extraToggles = array();
1020 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1021 if( $wgUseRCPatrol ) {
1022 $extraToggles[] = 'hidepatrolled';
1023 $extraToggles[] = 'watchlisthidepatrolled';
1024 }
1025 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1026 }
1027
1028
1029 /**
1030 * Get blocking information
1031 * @private
1032 * @param $bFromSlave \bool Whether to check the slave database first. To
1033 * improve performance, non-critical checks are done
1034 * against slaves. Check when actually saving should be
1035 * done against master.
1036 */
1037 function getBlockedStatus( $bFromSlave = true ) {
1038 global $wgEnableSorbs, $wgProxyWhitelist;
1039
1040 if ( -1 != $this->mBlockedby ) {
1041 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1042 return;
1043 }
1044
1045 wfProfileIn( __METHOD__ );
1046 wfDebug( __METHOD__.": checking...\n" );
1047
1048 // Initialize data...
1049 // Otherwise something ends up stomping on $this->mBlockedby when
1050 // things get lazy-loaded later, causing false positive block hits
1051 // due to -1 !== 0. Probably session-related... Nothing should be
1052 // overwriting mBlockedby, surely?
1053 $this->load();
1054
1055 $this->mBlockedby = 0;
1056 $this->mHideName = 0;
1057 $this->mAllowUsertalk = 0;
1058 $ip = wfGetIP();
1059
1060 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1061 # Exempt from all types of IP-block
1062 $ip = '';
1063 }
1064
1065 # User/IP blocking
1066 $this->mBlock = new Block();
1067 $this->mBlock->fromMaster( !$bFromSlave );
1068 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1069 wfDebug( __METHOD__.": Found block.\n" );
1070 $this->mBlockedby = $this->mBlock->mBy;
1071 $this->mBlockreason = $this->mBlock->mReason;
1072 $this->mHideName = $this->mBlock->mHideName;
1073 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1074 if ( $this->isLoggedIn() ) {
1075 $this->spreadBlock();
1076 }
1077 } else {
1078 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1079 // apply to users. Note that the existence of $this->mBlock is not used to
1080 // check for edit blocks, $this->mBlockedby is instead.
1081 }
1082
1083 # Proxy blocking
1084 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1085 # Local list
1086 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1087 $this->mBlockedby = wfMsg( 'proxyblocker' );
1088 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1089 }
1090
1091 # DNSBL
1092 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1093 if ( $this->inSorbsBlacklist( $ip ) ) {
1094 $this->mBlockedby = wfMsg( 'sorbs' );
1095 $this->mBlockreason = wfMsg( 'sorbsreason' );
1096 }
1097 }
1098 }
1099
1100 # Extensions
1101 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1102
1103 wfProfileOut( __METHOD__ );
1104 }
1105
1106 /**
1107 * Whether the given IP is in the SORBS blacklist.
1108 *
1109 * @param $ip \string IP to check
1110 * @return \bool True if blacklisted.
1111 */
1112 function inSorbsBlacklist( $ip ) {
1113 global $wgEnableSorbs, $wgSorbsUrl;
1114
1115 return $wgEnableSorbs &&
1116 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1117 }
1118
1119 /**
1120 * Whether the given IP is in a given DNS blacklist.
1121 *
1122 * @param $ip \string IP to check
1123 * @param $base \string URL of the DNS blacklist
1124 * @return \bool True if blacklisted.
1125 */
1126 function inDnsBlacklist( $ip, $base ) {
1127 wfProfileIn( __METHOD__ );
1128
1129 $found = false;
1130 $host = '';
1131 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1132 if( IP::isIPv4($ip) ) {
1133 # Make hostname
1134 $host = "$ip.$base";
1135
1136 # Send query
1137 $ipList = gethostbynamel( $host );
1138
1139 if( $ipList ) {
1140 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1141 $found = true;
1142 } else {
1143 wfDebug( "Requested $host, not found in $base.\n" );
1144 }
1145 }
1146
1147 wfProfileOut( __METHOD__ );
1148 return $found;
1149 }
1150
1151 /**
1152 * Is this user subject to rate limiting?
1153 *
1154 * @return \bool True if rate limited
1155 */
1156 public function isPingLimitable() {
1157 global $wgRateLimitsExcludedGroups;
1158 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1159 // Deprecated, but kept for backwards-compatibility config
1160 return false;
1161 }
1162 return !$this->isAllowed('noratelimit');
1163 }
1164
1165 /**
1166 * Primitive rate limits: enforce maximum actions per time period
1167 * to put a brake on flooding.
1168 *
1169 * @note When using a shared cache like memcached, IP-address
1170 * last-hit counters will be shared across wikis.
1171 *
1172 * @param $action \string Action to enforce; 'edit' if unspecified
1173 * @return \bool True if a rate limiter was tripped
1174 */
1175 function pingLimiter( $action='edit' ) {
1176
1177 # Call the 'PingLimiter' hook
1178 $result = false;
1179 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1180 return $result;
1181 }
1182
1183 global $wgRateLimits;
1184 if( !isset( $wgRateLimits[$action] ) ) {
1185 return false;
1186 }
1187
1188 # Some groups shouldn't trigger the ping limiter, ever
1189 if( !$this->isPingLimitable() )
1190 return false;
1191
1192 global $wgMemc, $wgRateLimitLog;
1193 wfProfileIn( __METHOD__ );
1194
1195 $limits = $wgRateLimits[$action];
1196 $keys = array();
1197 $id = $this->getId();
1198 $ip = wfGetIP();
1199 $userLimit = false;
1200
1201 if( isset( $limits['anon'] ) && $id == 0 ) {
1202 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1203 }
1204
1205 if( isset( $limits['user'] ) && $id != 0 ) {
1206 $userLimit = $limits['user'];
1207 }
1208 if( $this->isNewbie() ) {
1209 if( isset( $limits['newbie'] ) && $id != 0 ) {
1210 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1211 }
1212 if( isset( $limits['ip'] ) ) {
1213 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1214 }
1215 $matches = array();
1216 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1217 $subnet = $matches[1];
1218 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1219 }
1220 }
1221 // Check for group-specific permissions
1222 // If more than one group applies, use the group with the highest limit
1223 foreach ( $this->getGroups() as $group ) {
1224 if ( isset( $limits[$group] ) ) {
1225 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1226 $userLimit = $limits[$group];
1227 }
1228 }
1229 }
1230 // Set the user limit key
1231 if ( $userLimit !== false ) {
1232 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1233 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1234 }
1235
1236 $triggered = false;
1237 foreach( $keys as $key => $limit ) {
1238 list( $max, $period ) = $limit;
1239 $summary = "(limit $max in {$period}s)";
1240 $count = $wgMemc->get( $key );
1241 if( $count ) {
1242 if( $count > $max ) {
1243 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1244 if( $wgRateLimitLog ) {
1245 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1246 }
1247 $triggered = true;
1248 } else {
1249 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1250 }
1251 } else {
1252 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1253 $wgMemc->add( $key, 1, intval( $period ) );
1254 }
1255 $wgMemc->incr( $key );
1256 }
1257
1258 wfProfileOut( __METHOD__ );
1259 return $triggered;
1260 }
1261
1262 /**
1263 * Check if user is blocked
1264 *
1265 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1266 * @return \bool True if blocked, false otherwise
1267 */
1268 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1269 wfDebug( "User::isBlocked: enter\n" );
1270 $this->getBlockedStatus( $bFromSlave );
1271 return $this->mBlockedby !== 0;
1272 }
1273
1274 /**
1275 * Check if user is blocked from editing a particular article
1276 *
1277 * @param $title \string Title to check
1278 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1279 * @return \bool True if blocked, false otherwise
1280 */
1281 function isBlockedFrom( $title, $bFromSlave = false ) {
1282 global $wgBlockAllowsUTEdit;
1283 wfProfileIn( __METHOD__ );
1284 wfDebug( __METHOD__.": enter\n" );
1285
1286 wfDebug( __METHOD__.": asking isBlocked()\n" );
1287 $blocked = $this->isBlocked( $bFromSlave );
1288 $allowUsertalk = ($wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false);
1289 # If a user's name is suppressed, they cannot make edits anywhere
1290 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1291 $title->getNamespace() == NS_USER_TALK ) {
1292 $blocked = false;
1293 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1294 }
1295 wfProfileOut( __METHOD__ );
1296 return $blocked;
1297 }
1298
1299 /**
1300 * If user is blocked, return the name of the user who placed the block
1301 * @return \string name of blocker
1302 */
1303 function blockedBy() {
1304 $this->getBlockedStatus();
1305 return $this->mBlockedby;
1306 }
1307
1308 /**
1309 * If user is blocked, return the specified reason for the block
1310 * @return \string Blocking reason
1311 */
1312 function blockedFor() {
1313 $this->getBlockedStatus();
1314 return $this->mBlockreason;
1315 }
1316
1317 /**
1318 * Check if user is blocked on all wikis.
1319 * Do not use for actual edit permission checks!
1320 * This is intented for quick UI checks.
1321 *
1322 * @param $ip \type{\string} IP address, uses current client if none given
1323 * @return \type{\bool} True if blocked, false otherwise
1324 */
1325 function isBlockedGlobally( $ip = '' ) {
1326 if( $this->mBlockedGlobally !== null ) {
1327 return $this->mBlockedGlobally;
1328 }
1329 // User is already an IP?
1330 if( IP::isIPAddress( $this->getName() ) ) {
1331 $ip = $this->getName();
1332 } else if( !$ip ) {
1333 $ip = wfGetIP();
1334 }
1335 $blocked = false;
1336 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1337 $this->mBlockedGlobally = (bool)$blocked;
1338 return $this->mBlockedGlobally;
1339 }
1340
1341 /**
1342 * Check if user account is locked
1343 *
1344 * @return \type{\bool} True if locked, false otherwise
1345 */
1346 function isLocked() {
1347 if( $this->mLocked !== null ) {
1348 return $this->mLocked;
1349 }
1350 global $wgAuth;
1351 $authUser = $wgAuth->getUserInstance( $this );
1352 $this->mLocked = (bool)$authUser->isLocked();
1353 return $this->mLocked;
1354 }
1355
1356 /**
1357 * Check if user account is hidden
1358 *
1359 * @return \type{\bool} True if hidden, false otherwise
1360 */
1361 function isHidden() {
1362 if( $this->mHideName !== null ) {
1363 return $this->mHideName;
1364 }
1365 $this->getBlockedStatus();
1366 if( !$this->mHideName ) {
1367 global $wgAuth;
1368 $authUser = $wgAuth->getUserInstance( $this );
1369 $this->mHideName = (bool)$authUser->isHidden();
1370 }
1371 return $this->mHideName;
1372 }
1373
1374 /**
1375 * Get the user's ID.
1376 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1377 */
1378 function getId() {
1379 if( $this->mId === null and $this->mName !== null
1380 and User::isIP( $this->mName ) ) {
1381 // Special case, we know the user is anonymous
1382 return 0;
1383 } elseif( $this->mId === null ) {
1384 // Don't load if this was initialized from an ID
1385 $this->load();
1386 }
1387 return $this->mId;
1388 }
1389
1390 /**
1391 * Set the user and reload all fields according to a given ID
1392 * @param $v \int User ID to reload
1393 */
1394 function setId( $v ) {
1395 $this->mId = $v;
1396 $this->clearInstanceCache( 'id' );
1397 }
1398
1399 /**
1400 * Get the user name, or the IP of an anonymous user
1401 * @return \string User's name or IP address
1402 */
1403 function getName() {
1404 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1405 # Special case optimisation
1406 return $this->mName;
1407 } else {
1408 $this->load();
1409 if ( $this->mName === false ) {
1410 # Clean up IPs
1411 $this->mName = IP::sanitizeIP( wfGetIP() );
1412 }
1413 return $this->mName;
1414 }
1415 }
1416
1417 /**
1418 * Set the user name.
1419 *
1420 * This does not reload fields from the database according to the given
1421 * name. Rather, it is used to create a temporary "nonexistent user" for
1422 * later addition to the database. It can also be used to set the IP
1423 * address for an anonymous user to something other than the current
1424 * remote IP.
1425 *
1426 * @note User::newFromName() has rougly the same function, when the named user
1427 * does not exist.
1428 * @param $str \string New user name to set
1429 */
1430 function setName( $str ) {
1431 $this->load();
1432 $this->mName = $str;
1433 }
1434
1435 /**
1436 * Get the user's name escaped by underscores.
1437 * @return \string Username escaped by underscores.
1438 */
1439 function getTitleKey() {
1440 return str_replace( ' ', '_', $this->getName() );
1441 }
1442
1443 /**
1444 * Check if the user has new messages.
1445 * @return \bool True if the user has new messages
1446 */
1447 function getNewtalk() {
1448 $this->load();
1449
1450 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1451 if( $this->mNewtalk === -1 ) {
1452 $this->mNewtalk = false; # reset talk page status
1453
1454 # Check memcached separately for anons, who have no
1455 # entire User object stored in there.
1456 if( !$this->mId ) {
1457 global $wgMemc;
1458 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1459 $newtalk = $wgMemc->get( $key );
1460 if( strval( $newtalk ) !== '' ) {
1461 $this->mNewtalk = (bool)$newtalk;
1462 } else {
1463 // Since we are caching this, make sure it is up to date by getting it
1464 // from the master
1465 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1466 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1467 }
1468 } else {
1469 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1470 }
1471 }
1472
1473 return (bool)$this->mNewtalk;
1474 }
1475
1476 /**
1477 * Return the talk page(s) this user has new messages on.
1478 * @return \type{\arrayof{\string}} Array of page URLs
1479 */
1480 function getNewMessageLinks() {
1481 $talks = array();
1482 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1483 return $talks;
1484
1485 if (!$this->getNewtalk())
1486 return array();
1487 $up = $this->getUserPage();
1488 $utp = $up->getTalkPage();
1489 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1490 }
1491
1492
1493 /**
1494 * Internal uncached check for new messages
1495 *
1496 * @see getNewtalk()
1497 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1498 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1499 * @param $fromMaster \bool true to fetch from the master, false for a slave
1500 * @return \bool True if the user has new messages
1501 * @private
1502 */
1503 function checkNewtalk( $field, $id, $fromMaster = false ) {
1504 if ( $fromMaster ) {
1505 $db = wfGetDB( DB_MASTER );
1506 } else {
1507 $db = wfGetDB( DB_SLAVE );
1508 }
1509 $ok = $db->selectField( 'user_newtalk', $field,
1510 array( $field => $id ), __METHOD__ );
1511 return $ok !== false;
1512 }
1513
1514 /**
1515 * Add or update the new messages flag
1516 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1517 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1518 * @return \bool True if successful, false otherwise
1519 * @private
1520 */
1521 function updateNewtalk( $field, $id ) {
1522 $dbw = wfGetDB( DB_MASTER );
1523 $dbw->insert( 'user_newtalk',
1524 array( $field => $id ),
1525 __METHOD__,
1526 'IGNORE' );
1527 if ( $dbw->affectedRows() ) {
1528 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1529 return true;
1530 } else {
1531 wfDebug( __METHOD__." already set ($field, $id)\n" );
1532 return false;
1533 }
1534 }
1535
1536 /**
1537 * Clear the new messages flag for the given user
1538 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1539 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1540 * @return \bool True if successful, false otherwise
1541 * @private
1542 */
1543 function deleteNewtalk( $field, $id ) {
1544 $dbw = wfGetDB( DB_MASTER );
1545 $dbw->delete( 'user_newtalk',
1546 array( $field => $id ),
1547 __METHOD__ );
1548 if ( $dbw->affectedRows() ) {
1549 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1550 return true;
1551 } else {
1552 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1553 return false;
1554 }
1555 }
1556
1557 /**
1558 * Update the 'You have new messages!' status.
1559 * @param $val \bool Whether the user has new messages
1560 */
1561 function setNewtalk( $val ) {
1562 if( wfReadOnly() ) {
1563 return;
1564 }
1565
1566 $this->load();
1567 $this->mNewtalk = $val;
1568
1569 if( $this->isAnon() ) {
1570 $field = 'user_ip';
1571 $id = $this->getName();
1572 } else {
1573 $field = 'user_id';
1574 $id = $this->getId();
1575 }
1576 global $wgMemc;
1577
1578 if( $val ) {
1579 $changed = $this->updateNewtalk( $field, $id );
1580 } else {
1581 $changed = $this->deleteNewtalk( $field, $id );
1582 }
1583
1584 if( $this->isAnon() ) {
1585 // Anons have a separate memcached space, since
1586 // user records aren't kept for them.
1587 $key = wfMemcKey( 'newtalk', 'ip', $id );
1588 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1589 }
1590 if ( $changed ) {
1591 $this->invalidateCache();
1592 }
1593 }
1594
1595 /**
1596 * Generate a current or new-future timestamp to be stored in the
1597 * user_touched field when we update things.
1598 * @return \string Timestamp in TS_MW format
1599 */
1600 private static function newTouchedTimestamp() {
1601 global $wgClockSkewFudge;
1602 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1603 }
1604
1605 /**
1606 * Clear user data from memcached.
1607 * Use after applying fun updates to the database; caller's
1608 * responsibility to update user_touched if appropriate.
1609 *
1610 * Called implicitly from invalidateCache() and saveSettings().
1611 */
1612 private function clearSharedCache() {
1613 $this->load();
1614 if( $this->mId ) {
1615 global $wgMemc;
1616 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1617 }
1618 }
1619
1620 /**
1621 * Immediately touch the user data cache for this account.
1622 * Updates user_touched field, and removes account data from memcached
1623 * for reload on the next hit.
1624 */
1625 function invalidateCache() {
1626 $this->load();
1627 if( $this->mId ) {
1628 $this->mTouched = self::newTouchedTimestamp();
1629
1630 $dbw = wfGetDB( DB_MASTER );
1631 $dbw->update( 'user',
1632 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1633 array( 'user_id' => $this->mId ),
1634 __METHOD__ );
1635
1636 $this->clearSharedCache();
1637 }
1638 }
1639
1640 /**
1641 * Validate the cache for this account.
1642 * @param $timestamp \string A timestamp in TS_MW format
1643 */
1644 function validateCache( $timestamp ) {
1645 $this->load();
1646 return ($timestamp >= $this->mTouched);
1647 }
1648
1649 /**
1650 * Get the user touched timestamp
1651 */
1652 function getTouched() {
1653 $this->load();
1654 return $this->mTouched;
1655 }
1656
1657 /**
1658 * Set the password and reset the random token.
1659 * Calls through to authentication plugin if necessary;
1660 * will have no effect if the auth plugin refuses to
1661 * pass the change through or if the legal password
1662 * checks fail.
1663 *
1664 * As a special case, setting the password to null
1665 * wipes it, so the account cannot be logged in until
1666 * a new password is set, for instance via e-mail.
1667 *
1668 * @param $str \string New password to set
1669 * @throws PasswordError on failure
1670 */
1671 function setPassword( $str ) {
1672 global $wgAuth;
1673
1674 if( $str !== null ) {
1675 if( !$wgAuth->allowPasswordChange() ) {
1676 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1677 }
1678
1679 if( !$this->isValidPassword( $str ) ) {
1680 global $wgMinimalPasswordLength;
1681 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1682 $wgMinimalPasswordLength ) );
1683 }
1684 }
1685
1686 if( !$wgAuth->setPassword( $this, $str ) ) {
1687 throw new PasswordError( wfMsg( 'externaldberror' ) );
1688 }
1689
1690 $this->setInternalPassword( $str );
1691
1692 return true;
1693 }
1694
1695 /**
1696 * Set the password and reset the random token unconditionally.
1697 *
1698 * @param $str \string New password to set
1699 */
1700 function setInternalPassword( $str ) {
1701 $this->load();
1702 $this->setToken();
1703
1704 if( $str === null ) {
1705 // Save an invalid hash...
1706 $this->mPassword = '';
1707 } else {
1708 $this->mPassword = self::crypt( $str );
1709 }
1710 $this->mNewpassword = '';
1711 $this->mNewpassTime = null;
1712 }
1713
1714 /**
1715 * Get the user's current token.
1716 * @return \string Token
1717 */
1718 function getToken() {
1719 $this->load();
1720 return $this->mToken;
1721 }
1722
1723 /**
1724 * Set the random token (used for persistent authentication)
1725 * Called from loadDefaults() among other places.
1726 *
1727 * @param $token \string If specified, set the token to this value
1728 * @private
1729 */
1730 function setToken( $token = false ) {
1731 global $wgSecretKey, $wgProxyKey;
1732 $this->load();
1733 if ( !$token ) {
1734 if ( $wgSecretKey ) {
1735 $key = $wgSecretKey;
1736 } elseif ( $wgProxyKey ) {
1737 $key = $wgProxyKey;
1738 } else {
1739 $key = microtime();
1740 }
1741 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1742 } else {
1743 $this->mToken = $token;
1744 }
1745 }
1746
1747 /**
1748 * Set the cookie password
1749 *
1750 * @param $str \string New cookie password
1751 * @private
1752 */
1753 function setCookiePassword( $str ) {
1754 $this->load();
1755 $this->mCookiePassword = md5( $str );
1756 }
1757
1758 /**
1759 * Set the password for a password reminder or new account email
1760 *
1761 * @param $str \string New password to set
1762 * @param $throttle \bool If true, reset the throttle timestamp to the present
1763 */
1764 function setNewpassword( $str, $throttle = true ) {
1765 $this->load();
1766 $this->mNewpassword = self::crypt( $str );
1767 if ( $throttle ) {
1768 $this->mNewpassTime = wfTimestampNow();
1769 }
1770 }
1771
1772 /**
1773 * Has password reminder email been sent within the last
1774 * $wgPasswordReminderResendTime hours?
1775 * @return \bool True or false
1776 */
1777 function isPasswordReminderThrottled() {
1778 global $wgPasswordReminderResendTime;
1779 $this->load();
1780 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1781 return false;
1782 }
1783 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1784 return time() < $expiry;
1785 }
1786
1787 /**
1788 * Get the user's e-mail address
1789 * @return \string User's email address
1790 */
1791 function getEmail() {
1792 $this->load();
1793 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1794 return $this->mEmail;
1795 }
1796
1797 /**
1798 * Get the timestamp of the user's e-mail authentication
1799 * @return \string TS_MW timestamp
1800 */
1801 function getEmailAuthenticationTimestamp() {
1802 $this->load();
1803 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1804 return $this->mEmailAuthenticated;
1805 }
1806
1807 /**
1808 * Set the user's e-mail address
1809 * @param $str \string New e-mail address
1810 */
1811 function setEmail( $str ) {
1812 $this->load();
1813 $this->mEmail = $str;
1814 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1815 }
1816
1817 /**
1818 * Get the user's real name
1819 * @return \string User's real name
1820 */
1821 function getRealName() {
1822 $this->load();
1823 return $this->mRealName;
1824 }
1825
1826 /**
1827 * Set the user's real name
1828 * @param $str \string New real name
1829 */
1830 function setRealName( $str ) {
1831 $this->load();
1832 $this->mRealName = $str;
1833 }
1834
1835 /**
1836 * Get the user's current setting for a given option.
1837 *
1838 * @param $oname \string The option to check
1839 * @param $defaultOverride \string A default value returned if the option does not exist
1840 * @return \string User's current value for the option
1841 * @see getBoolOption()
1842 * @see getIntOption()
1843 */
1844 function getOption( $oname, $defaultOverride = '' ) {
1845 $this->load();
1846
1847 if ( is_null( $this->mOptions ) ) {
1848 if($defaultOverride != '') {
1849 return $defaultOverride;
1850 }
1851 $this->mOptions = User::getDefaultOptions();
1852 }
1853
1854 if ( array_key_exists( $oname, $this->mOptions ) ) {
1855 return trim( $this->mOptions[$oname] );
1856 } else {
1857 return $defaultOverride;
1858 }
1859 }
1860
1861 /**
1862 * Get the user's current setting for a given option, as a boolean value.
1863 *
1864 * @param $oname \string The option to check
1865 * @return \bool User's current value for the option
1866 * @see getOption()
1867 */
1868 function getBoolOption( $oname ) {
1869 return (bool)$this->getOption( $oname );
1870 }
1871
1872
1873 /**
1874 * Get the user's current setting for a given option, as a boolean value.
1875 *
1876 * @param $oname \string The option to check
1877 * @param $defaultOverride \int A default value returned if the option does not exist
1878 * @return \int User's current value for the option
1879 * @see getOption()
1880 */
1881 function getIntOption( $oname, $defaultOverride=0 ) {
1882 $val = $this->getOption( $oname );
1883 if( $val == '' ) {
1884 $val = $defaultOverride;
1885 }
1886 return intval( $val );
1887 }
1888
1889 /**
1890 * Set the given option for a user.
1891 *
1892 * @param $oname \string The option to set
1893 * @param $val \mixed New value to set
1894 */
1895 function setOption( $oname, $val ) {
1896 $this->load();
1897 if ( is_null( $this->mOptions ) ) {
1898 $this->mOptions = User::getDefaultOptions();
1899 }
1900 if ( $oname == 'skin' ) {
1901 # Clear cached skin, so the new one displays immediately in Special:Preferences
1902 unset( $this->mSkin );
1903 }
1904 // Filter out any newlines that may have passed through input validation.
1905 // Newlines are used to separate items in the options blob.
1906 if( $val ) {
1907 $val = str_replace( "\r\n", "\n", $val );
1908 $val = str_replace( "\r", "\n", $val );
1909 $val = str_replace( "\n", " ", $val );
1910 }
1911 // Explicitly NULL values should refer to defaults
1912 global $wgDefaultUserOptions;
1913 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1914 $val = $wgDefaultUserOptions[$oname];
1915 }
1916 $this->mOptions[$oname] = $val;
1917 }
1918
1919 /**
1920 * Reset all options to the site defaults
1921 */
1922 function restoreOptions() {
1923 $this->mOptions = User::getDefaultOptions();
1924 }
1925
1926 /**
1927 * Get the user's preferred date format.
1928 * @return \string User's preferred date format
1929 */
1930 function getDatePreference() {
1931 // Important migration for old data rows
1932 if ( is_null( $this->mDatePreference ) ) {
1933 global $wgLang;
1934 $value = $this->getOption( 'date' );
1935 $map = $wgLang->getDatePreferenceMigrationMap();
1936 if ( isset( $map[$value] ) ) {
1937 $value = $map[$value];
1938 }
1939 $this->mDatePreference = $value;
1940 }
1941 return $this->mDatePreference;
1942 }
1943
1944 /**
1945 * Get the permissions this user has.
1946 * @return \type{\arrayof{\string}} Array of permission names
1947 */
1948 function getRights() {
1949 if ( is_null( $this->mRights ) ) {
1950 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1951 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1952 // Force reindexation of rights when a hook has unset one of them
1953 $this->mRights = array_values( $this->mRights );
1954 }
1955 return $this->mRights;
1956 }
1957
1958 /**
1959 * Get the list of explicit group memberships this user has.
1960 * The implicit * and user groups are not included.
1961 * @return \type{\arrayof{\string}} Array of internal group names
1962 */
1963 function getGroups() {
1964 $this->load();
1965 return $this->mGroups;
1966 }
1967
1968 /**
1969 * Get the list of implicit group memberships this user has.
1970 * This includes all explicit groups, plus 'user' if logged in,
1971 * '*' for all accounts and autopromoted groups
1972 * @param $recache \bool Whether to avoid the cache
1973 * @return \type{\arrayof{\string}} Array of internal group names
1974 */
1975 function getEffectiveGroups( $recache = false ) {
1976 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1977 $this->mEffectiveGroups = $this->getGroups();
1978 $this->mEffectiveGroups[] = '*';
1979 if( $this->getId() ) {
1980 $this->mEffectiveGroups[] = 'user';
1981
1982 $this->mEffectiveGroups = array_unique( array_merge(
1983 $this->mEffectiveGroups,
1984 Autopromote::getAutopromoteGroups( $this )
1985 ) );
1986
1987 # Hook for additional groups
1988 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1989 }
1990 }
1991 return $this->mEffectiveGroups;
1992 }
1993
1994 /**
1995 * Get the user's edit count.
1996 * @return \int User'e edit count
1997 */
1998 function getEditCount() {
1999 if ($this->mId) {
2000 if ( !isset( $this->mEditCount ) ) {
2001 /* Populate the count, if it has not been populated yet */
2002 $this->mEditCount = User::edits($this->mId);
2003 }
2004 return $this->mEditCount;
2005 } else {
2006 /* nil */
2007 return null;
2008 }
2009 }
2010
2011 /**
2012 * Add the user to the given group.
2013 * This takes immediate effect.
2014 * @param $group \string Name of the group to add
2015 */
2016 function addGroup( $group ) {
2017 $dbw = wfGetDB( DB_MASTER );
2018 if( $this->getId() ) {
2019 $dbw->insert( 'user_groups',
2020 array(
2021 'ug_user' => $this->getID(),
2022 'ug_group' => $group,
2023 ),
2024 'User::addGroup',
2025 array( 'IGNORE' ) );
2026 }
2027
2028 $this->loadGroups();
2029 $this->mGroups[] = $group;
2030 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2031
2032 $this->invalidateCache();
2033 }
2034
2035 /**
2036 * Remove the user from the given group.
2037 * This takes immediate effect.
2038 * @param $group \string Name of the group to remove
2039 */
2040 function removeGroup( $group ) {
2041 $this->load();
2042 $dbw = wfGetDB( DB_MASTER );
2043 $dbw->delete( 'user_groups',
2044 array(
2045 'ug_user' => $this->getID(),
2046 'ug_group' => $group,
2047 ),
2048 'User::removeGroup' );
2049
2050 $this->loadGroups();
2051 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2052 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2053
2054 $this->invalidateCache();
2055 }
2056
2057
2058 /**
2059 * Get whether the user is logged in
2060 * @return \bool True or false
2061 */
2062 function isLoggedIn() {
2063 return $this->getID() != 0;
2064 }
2065
2066 /**
2067 * Get whether the user is anonymous
2068 * @return \bool True or false
2069 */
2070 function isAnon() {
2071 return !$this->isLoggedIn();
2072 }
2073
2074 /**
2075 * Get whether the user is a bot
2076 * @return \bool True or false
2077 * @deprecated
2078 */
2079 function isBot() {
2080 wfDeprecated( __METHOD__ );
2081 return $this->isAllowed( 'bot' );
2082 }
2083
2084 /**
2085 * Check if user is allowed to access a feature / make an action
2086 * @param $action \string action to be checked
2087 * @return \bool True if action is allowed, else false
2088 */
2089 function isAllowed( $action = '' ) {
2090 if ( $action === '' )
2091 return true; // In the spirit of DWIM
2092 # Patrolling may not be enabled
2093 if( $action === 'patrol' || $action === 'autopatrol' ) {
2094 global $wgUseRCPatrol, $wgUseNPPatrol;
2095 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2096 return true;
2097 }
2098 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2099 # by misconfiguration: 0 == 'foo'
2100 return in_array( $action, $this->getRights(), true );
2101 }
2102
2103 /**
2104 * Check whether to enable recent changes patrol features for this user
2105 * @return \bool True or false
2106 */
2107 public function useRCPatrol() {
2108 global $wgUseRCPatrol;
2109 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2110 }
2111
2112 /**
2113 * Check whether to enable new pages patrol features for this user
2114 * @return \bool True or false
2115 */
2116 public function useNPPatrol() {
2117 global $wgUseRCPatrol, $wgUseNPPatrol;
2118 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2119 }
2120
2121 /**
2122 * Get the current skin, loading it if required
2123 * @return \type{Skin} Current skin
2124 * @todo FIXME : need to check the old failback system [AV]
2125 */
2126 function &getSkin() {
2127 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2128 if ( ! isset( $this->mSkin ) ) {
2129 wfProfileIn( __METHOD__ );
2130
2131 if( $wgAllowUserSkin ) {
2132 # get the user skin
2133 $userSkin = $this->getOption( 'skin' );
2134 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2135 } else {
2136 # if we're not allowing users to override, then use the default
2137 $userSkin = $wgDefaultSkin;
2138 }
2139
2140 $this->mSkin =& Skin::newFromKey( $userSkin );
2141 wfProfileOut( __METHOD__ );
2142 }
2143 return $this->mSkin;
2144 }
2145
2146 /**
2147 * Check the watched status of an article.
2148 * @param $title \type{Title} Title of the article to look at
2149 * @return \bool True if article is watched
2150 */
2151 function isWatched( $title ) {
2152 $wl = WatchedItem::fromUserTitle( $this, $title );
2153 return $wl->isWatched();
2154 }
2155
2156 /**
2157 * Watch an article.
2158 * @param $title \type{Title} Title of the article to look at
2159 */
2160 function addWatch( $title ) {
2161 $wl = WatchedItem::fromUserTitle( $this, $title );
2162 $wl->addWatch();
2163 $this->invalidateCache();
2164 }
2165
2166 /**
2167 * Stop watching an article.
2168 * @param $title \type{Title} Title of the article to look at
2169 */
2170 function removeWatch( $title ) {
2171 $wl = WatchedItem::fromUserTitle( $this, $title );
2172 $wl->removeWatch();
2173 $this->invalidateCache();
2174 }
2175
2176 /**
2177 * Clear the user's notification timestamp for the given title.
2178 * If e-notif e-mails are on, they will receive notification mails on
2179 * the next change of the page if it's watched etc.
2180 * @param $title \type{Title} Title of the article to look at
2181 */
2182 function clearNotification( &$title ) {
2183 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2184
2185 # Do nothing if the database is locked to writes
2186 if( wfReadOnly() ) {
2187 return;
2188 }
2189
2190 if ($title->getNamespace() == NS_USER_TALK &&
2191 $title->getText() == $this->getName() ) {
2192 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2193 return;
2194 $this->setNewtalk( false );
2195 }
2196
2197 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2198 return;
2199 }
2200
2201 if( $this->isAnon() ) {
2202 // Nothing else to do...
2203 return;
2204 }
2205
2206 // Only update the timestamp if the page is being watched.
2207 // The query to find out if it is watched is cached both in memcached and per-invocation,
2208 // and when it does have to be executed, it can be on a slave
2209 // If this is the user's newtalk page, we always update the timestamp
2210 if ($title->getNamespace() == NS_USER_TALK &&
2211 $title->getText() == $wgUser->getName())
2212 {
2213 $watched = true;
2214 } elseif ( $this->getId() == $wgUser->getId() ) {
2215 $watched = $title->userIsWatching();
2216 } else {
2217 $watched = true;
2218 }
2219
2220 // If the page is watched by the user (or may be watched), update the timestamp on any
2221 // any matching rows
2222 if ( $watched ) {
2223 $dbw = wfGetDB( DB_MASTER );
2224 $dbw->update( 'watchlist',
2225 array( /* SET */
2226 'wl_notificationtimestamp' => NULL
2227 ), array( /* WHERE */
2228 'wl_title' => $title->getDBkey(),
2229 'wl_namespace' => $title->getNamespace(),
2230 'wl_user' => $this->getID()
2231 ), __METHOD__
2232 );
2233 }
2234 }
2235
2236 /**
2237 * Resets all of the given user's page-change notification timestamps.
2238 * If e-notif e-mails are on, they will receive notification mails on
2239 * the next change of any watched page.
2240 *
2241 * @param $currentUser \int User ID
2242 */
2243 function clearAllNotifications( $currentUser ) {
2244 global $wgUseEnotif, $wgShowUpdatedMarker;
2245 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2246 $this->setNewtalk( false );
2247 return;
2248 }
2249 if( $currentUser != 0 ) {
2250 $dbw = wfGetDB( DB_MASTER );
2251 $dbw->update( 'watchlist',
2252 array( /* SET */
2253 'wl_notificationtimestamp' => NULL
2254 ), array( /* WHERE */
2255 'wl_user' => $currentUser
2256 ), __METHOD__
2257 );
2258 # We also need to clear here the "you have new message" notification for the own user_talk page
2259 # This is cleared one page view later in Article::viewUpdates();
2260 }
2261 }
2262
2263 /**
2264 * Encode this user's options as a string
2265 * @return \string Encoded options
2266 * @private
2267 */
2268 function encodeOptions() {
2269 $this->load();
2270 if ( is_null( $this->mOptions ) ) {
2271 $this->mOptions = User::getDefaultOptions();
2272 }
2273 $a = array();
2274 foreach ( $this->mOptions as $oname => $oval ) {
2275 array_push( $a, $oname.'='.$oval );
2276 }
2277 $s = implode( "\n", $a );
2278 return $s;
2279 }
2280
2281 /**
2282 * Set this user's options from an encoded string
2283 * @param $str \string Encoded options to import
2284 * @private
2285 */
2286 function decodeOptions( $str ) {
2287 $this->mOptions = array();
2288 $a = explode( "\n", $str );
2289 foreach ( $a as $s ) {
2290 $m = array();
2291 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2292 $this->mOptions[$m[1]] = $m[2];
2293 }
2294 }
2295 }
2296
2297 /**
2298 * Set a cookie on the user's client. Wrapper for
2299 * WebResponse::setCookie
2300 * @param $name \string Name of the cookie to set
2301 * @param $value \string Value to set
2302 * @param $exp \int Expiration time, as a UNIX time value;
2303 * if 0 or not specified, use the default $wgCookieExpiration
2304 */
2305 protected function setCookie( $name, $value, $exp=0 ) {
2306 global $wgRequest;
2307 $wgRequest->response()->setcookie( $name, $value, $exp );
2308 }
2309
2310 /**
2311 * Clear a cookie on the user's client
2312 * @param $name \string Name of the cookie to clear
2313 */
2314 protected function clearCookie( $name ) {
2315 $this->setCookie( $name, '', time() - 86400 );
2316 }
2317
2318 /**
2319 * Set the default cookies for this session on the user's client.
2320 */
2321 function setCookies() {
2322 $this->load();
2323 if ( 0 == $this->mId ) return;
2324 $session = array(
2325 'wsUserID' => $this->mId,
2326 'wsToken' => $this->mToken,
2327 'wsUserName' => $this->getName()
2328 );
2329 $cookies = array(
2330 'UserID' => $this->mId,
2331 'UserName' => $this->getName(),
2332 );
2333 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2334 $cookies['Token'] = $this->mToken;
2335 } else {
2336 $cookies['Token'] = false;
2337 }
2338
2339 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2340 #check for null, since the hook could cause a null value
2341 if ( !is_null( $session ) && isset( $_SESSION ) ){
2342 $_SESSION = $session + $_SESSION;
2343 }
2344 foreach ( $cookies as $name => $value ) {
2345 if ( $value === false ) {
2346 $this->clearCookie( $name );
2347 } else {
2348 $this->setCookie( $name, $value );
2349 }
2350 }
2351 }
2352
2353 /**
2354 * Log this user out.
2355 */
2356 function logout() {
2357 global $wgUser;
2358 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2359 $this->doLogout();
2360 }
2361 }
2362
2363 /**
2364 * Clear the user's cookies and session, and reset the instance cache.
2365 * @private
2366 * @see logout()
2367 */
2368 function doLogout() {
2369 $this->clearInstanceCache( 'defaults' );
2370
2371 $_SESSION['wsUserID'] = 0;
2372
2373 $this->clearCookie( 'UserID' );
2374 $this->clearCookie( 'Token' );
2375
2376 # Remember when user logged out, to prevent seeing cached pages
2377 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2378 }
2379
2380 /**
2381 * Save this user's settings into the database.
2382 * @todo Only rarely do all these fields need to be set!
2383 */
2384 function saveSettings() {
2385 $this->load();
2386 if ( wfReadOnly() ) { return; }
2387 if ( 0 == $this->mId ) { return; }
2388
2389 $this->mTouched = self::newTouchedTimestamp();
2390
2391 $dbw = wfGetDB( DB_MASTER );
2392 $dbw->update( 'user',
2393 array( /* SET */
2394 'user_name' => $this->mName,
2395 'user_password' => $this->mPassword,
2396 'user_newpassword' => $this->mNewpassword,
2397 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2398 'user_real_name' => $this->mRealName,
2399 'user_email' => $this->mEmail,
2400 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2401 'user_options' => $this->encodeOptions(),
2402 'user_touched' => $dbw->timestamp($this->mTouched),
2403 'user_token' => $this->mToken,
2404 'user_email_token' => $this->mEmailToken,
2405 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2406 ), array( /* WHERE */
2407 'user_id' => $this->mId
2408 ), __METHOD__
2409 );
2410 wfRunHooks( 'UserSaveSettings', array( $this ) );
2411 $this->clearSharedCache();
2412 $this->getUserPage()->invalidateCache();
2413 }
2414
2415 /**
2416 * If only this user's username is known, and it exists, return the user ID.
2417 */
2418 function idForName() {
2419 $s = trim( $this->getName() );
2420 if ( $s === '' ) return 0;
2421
2422 $dbr = wfGetDB( DB_SLAVE );
2423 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2424 if ( $id === false ) {
2425 $id = 0;
2426 }
2427 return $id;
2428 }
2429
2430 /**
2431 * Add a user to the database, return the user object
2432 *
2433 * @param $name \string Username to add
2434 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2435 * - password The user's password. Password logins will be disabled if this is omitted.
2436 * - newpassword A temporary password mailed to the user
2437 * - email The user's email address
2438 * - email_authenticated The email authentication timestamp
2439 * - real_name The user's real name
2440 * - options An associative array of non-default options
2441 * - token Random authentication token. Do not set.
2442 * - registration Registration timestamp. Do not set.
2443 *
2444 * @return \type{User} A new User object, or null if the username already exists
2445 */
2446 static function createNew( $name, $params = array() ) {
2447 $user = new User;
2448 $user->load();
2449 if ( isset( $params['options'] ) ) {
2450 $user->mOptions = $params['options'] + $user->mOptions;
2451 unset( $params['options'] );
2452 }
2453 $dbw = wfGetDB( DB_MASTER );
2454 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2455 $fields = array(
2456 'user_id' => $seqVal,
2457 'user_name' => $name,
2458 'user_password' => $user->mPassword,
2459 'user_newpassword' => $user->mNewpassword,
2460 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2461 'user_email' => $user->mEmail,
2462 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2463 'user_real_name' => $user->mRealName,
2464 'user_options' => $user->encodeOptions(),
2465 'user_token' => $user->mToken,
2466 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2467 'user_editcount' => 0,
2468 );
2469 foreach ( $params as $name => $value ) {
2470 $fields["user_$name"] = $value;
2471 }
2472 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2473 if ( $dbw->affectedRows() ) {
2474 $newUser = User::newFromId( $dbw->insertId() );
2475 } else {
2476 $newUser = null;
2477 }
2478 return $newUser;
2479 }
2480
2481 /**
2482 * Add this existing user object to the database
2483 */
2484 function addToDatabase() {
2485 $this->load();
2486 $dbw = wfGetDB( DB_MASTER );
2487 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2488 $dbw->insert( 'user',
2489 array(
2490 'user_id' => $seqVal,
2491 'user_name' => $this->mName,
2492 'user_password' => $this->mPassword,
2493 'user_newpassword' => $this->mNewpassword,
2494 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2495 'user_email' => $this->mEmail,
2496 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2497 'user_real_name' => $this->mRealName,
2498 'user_options' => $this->encodeOptions(),
2499 'user_token' => $this->mToken,
2500 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2501 'user_editcount' => 0,
2502 ), __METHOD__
2503 );
2504 $this->mId = $dbw->insertId();
2505
2506 // Clear instance cache other than user table data, which is already accurate
2507 $this->clearInstanceCache();
2508 }
2509
2510 /**
2511 * If this (non-anonymous) user is blocked, block any IP address
2512 * they've successfully logged in from.
2513 */
2514 function spreadBlock() {
2515 wfDebug( __METHOD__."()\n" );
2516 $this->load();
2517 if ( $this->mId == 0 ) {
2518 return;
2519 }
2520
2521 $userblock = Block::newFromDB( '', $this->mId );
2522 if ( !$userblock ) {
2523 return;
2524 }
2525
2526 $userblock->doAutoblock( wfGetIp() );
2527
2528 }
2529
2530 /**
2531 * Generate a string which will be different for any combination of
2532 * user options which would produce different parser output.
2533 * This will be used as part of the hash key for the parser cache,
2534 * so users will the same options can share the same cached data
2535 * safely.
2536 *
2537 * Extensions which require it should install 'PageRenderingHash' hook,
2538 * which will give them a chance to modify this key based on their own
2539 * settings.
2540 *
2541 * @return \string Page rendering hash
2542 */
2543 function getPageRenderingHash() {
2544 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2545 if( $this->mHash ){
2546 return $this->mHash;
2547 }
2548
2549 // stubthreshold is only included below for completeness,
2550 // it will always be 0 when this function is called by parsercache.
2551
2552 $confstr = $this->getOption( 'math' );
2553 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2554 if ( $wgUseDynamicDates ) {
2555 $confstr .= '!' . $this->getDatePreference();
2556 }
2557 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2558 $confstr .= '!' . $wgLang->getCode();
2559 $confstr .= '!' . $this->getOption( 'thumbsize' );
2560 // add in language specific options, if any
2561 $extra = $wgContLang->getExtraHashOptions();
2562 $confstr .= $extra;
2563
2564 $confstr .= $wgRenderHashAppend;
2565
2566 // Give a chance for extensions to modify the hash, if they have
2567 // extra options or other effects on the parser cache.
2568 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2569
2570 // Make it a valid memcached key fragment
2571 $confstr = str_replace( ' ', '_', $confstr );
2572 $this->mHash = $confstr;
2573 return $confstr;
2574 }
2575
2576 /**
2577 * Get whether the user is explicitly blocked from account creation.
2578 * @return \bool True if blocked
2579 */
2580 function isBlockedFromCreateAccount() {
2581 $this->getBlockedStatus();
2582 return $this->mBlock && $this->mBlock->mCreateAccount;
2583 }
2584
2585 /**
2586 * Get whether the user is blocked from using Special:Emailuser.
2587 * @return \bool True if blocked
2588 */
2589 function isBlockedFromEmailuser() {
2590 $this->getBlockedStatus();
2591 return $this->mBlock && $this->mBlock->mBlockEmail;
2592 }
2593
2594 /**
2595 * Get whether the user is allowed to create an account.
2596 * @return \bool True if allowed
2597 */
2598 function isAllowedToCreateAccount() {
2599 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2600 }
2601
2602 /**
2603 * @deprecated
2604 */
2605 function setLoaded( $loaded ) {
2606 wfDeprecated( __METHOD__ );
2607 }
2608
2609 /**
2610 * Get this user's personal page title.
2611 *
2612 * @return \type{Title} User's personal page title
2613 */
2614 function getUserPage() {
2615 return Title::makeTitle( NS_USER, $this->getName() );
2616 }
2617
2618 /**
2619 * Get this user's talk page title.
2620 *
2621 * @return \type{Title} User's talk page title
2622 */
2623 function getTalkPage() {
2624 $title = $this->getUserPage();
2625 return $title->getTalkPage();
2626 }
2627
2628 /**
2629 * Get the maximum valid user ID.
2630 * @return \int User ID
2631 * @static
2632 */
2633 function getMaxID() {
2634 static $res; // cache
2635
2636 if ( isset( $res ) )
2637 return $res;
2638 else {
2639 $dbr = wfGetDB( DB_SLAVE );
2640 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2641 }
2642 }
2643
2644 /**
2645 * Determine whether the user is a newbie. Newbies are either
2646 * anonymous IPs, or the most recently created accounts.
2647 * @return \bool True if the user is a newbie
2648 */
2649 function isNewbie() {
2650 return !$this->isAllowed( 'autoconfirmed' );
2651 }
2652
2653 /**
2654 * Is the user active? We check to see if they've made at least
2655 * X number of edits in the last Y days.
2656 *
2657 * @return \bool True if the user is active, false if not.
2658 */
2659 public function isActiveEditor() {
2660 global $wgActiveUserEditCount, $wgActiveUserDays;
2661 $dbr = wfGetDB( DB_SLAVE );
2662
2663 // Stolen without shame from RC
2664 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2665 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2666 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2667
2668 $res = $dbr->select( 'revision', '1',
2669 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2670 __METHOD__,
2671 array('LIMIT' => $wgActiveUserEditCount ) );
2672
2673 $count = $dbr->numRows($res);
2674 $dbr->freeResult($res);
2675
2676 return $count == $wgActiveUserEditCount;
2677 }
2678
2679 /**
2680 * Check to see if the given clear-text password is one of the accepted passwords
2681 * @param $password \string user password.
2682 * @return \bool True if the given password is correct, otherwise False.
2683 */
2684 function checkPassword( $password ) {
2685 global $wgAuth;
2686 $this->load();
2687
2688 // Even though we stop people from creating passwords that
2689 // are shorter than this, doesn't mean people wont be able
2690 // to. Certain authentication plugins do NOT want to save
2691 // domain passwords in a mysql database, so we should
2692 // check this (incase $wgAuth->strict() is false).
2693 if( !$this->isValidPassword( $password ) ) {
2694 return false;
2695 }
2696
2697 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2698 return true;
2699 } elseif( $wgAuth->strict() ) {
2700 /* Auth plugin doesn't allow local authentication */
2701 return false;
2702 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2703 /* Auth plugin doesn't allow local authentication for this user name */
2704 return false;
2705 }
2706 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2707 return true;
2708 } elseif ( function_exists( 'iconv' ) ) {
2709 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2710 # Check for this with iconv
2711 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2712 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2713 return true;
2714 }
2715 }
2716 return false;
2717 }
2718
2719 /**
2720 * Check if the given clear-text password matches the temporary password
2721 * sent by e-mail for password reset operations.
2722 * @return \bool True if matches, false otherwise
2723 */
2724 function checkTemporaryPassword( $plaintext ) {
2725 global $wgNewPasswordExpiry;
2726 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2727 $this->load();
2728 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2729 return ( time() < $expiry );
2730 } else {
2731 return false;
2732 }
2733 }
2734
2735 /**
2736 * Initialize (if necessary) and return a session token value
2737 * which can be used in edit forms to show that the user's
2738 * login credentials aren't being hijacked with a foreign form
2739 * submission.
2740 *
2741 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2742 * @return \string The new edit token
2743 */
2744 function editToken( $salt = '' ) {
2745 if ( $this->isAnon() ) {
2746 return EDIT_TOKEN_SUFFIX;
2747 } else {
2748 if( !isset( $_SESSION['wsEditToken'] ) ) {
2749 $token = $this->generateToken();
2750 $_SESSION['wsEditToken'] = $token;
2751 } else {
2752 $token = $_SESSION['wsEditToken'];
2753 }
2754 if( is_array( $salt ) ) {
2755 $salt = implode( '|', $salt );
2756 }
2757 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2758 }
2759 }
2760
2761 /**
2762 * Generate a looking random token for various uses.
2763 *
2764 * @param $salt \string Optional salt value
2765 * @return \string The new random token
2766 */
2767 function generateToken( $salt = '' ) {
2768 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2769 return md5( $token . $salt );
2770 }
2771
2772 /**
2773 * Check given value against the token value stored in the session.
2774 * A match should confirm that the form was submitted from the
2775 * user's own login session, not a form submission from a third-party
2776 * site.
2777 *
2778 * @param $val \string Input value to compare
2779 * @param $salt \string Optional function-specific data for hashing
2780 * @return \bool Whether the token matches
2781 */
2782 function matchEditToken( $val, $salt = '' ) {
2783 $sessionToken = $this->editToken( $salt );
2784 if ( $val != $sessionToken ) {
2785 wfDebug( "User::matchEditToken: broken session data\n" );
2786 }
2787 return $val == $sessionToken;
2788 }
2789
2790 /**
2791 * Check given value against the token value stored in the session,
2792 * ignoring the suffix.
2793 *
2794 * @param $val \string Input value to compare
2795 * @param $salt \string Optional function-specific data for hashing
2796 * @return \bool Whether the token matches
2797 */
2798 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2799 $sessionToken = $this->editToken( $salt );
2800 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2801 }
2802
2803 /**
2804 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2805 * mail to the user's given address.
2806 *
2807 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2808 */
2809 function sendConfirmationMail() {
2810 global $wgLang;
2811 $expiration = null; // gets passed-by-ref and defined in next line.
2812 $token = $this->confirmationToken( $expiration );
2813 $url = $this->confirmationTokenUrl( $token );
2814 $invalidateURL = $this->invalidationTokenUrl( $token );
2815 $this->saveSettings();
2816
2817 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2818 wfMsg( 'confirmemail_body',
2819 wfGetIP(),
2820 $this->getName(),
2821 $url,
2822 $wgLang->timeanddate( $expiration, false ),
2823 $invalidateURL ) );
2824 }
2825
2826 /**
2827 * Send an e-mail to this user's account. Does not check for
2828 * confirmed status or validity.
2829 *
2830 * @param $subject \string Message subject
2831 * @param $body \string Message body
2832 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2833 * @param $replyto \string Reply-To address
2834 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2835 */
2836 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2837 if( is_null( $from ) ) {
2838 global $wgPasswordSender;
2839 $from = $wgPasswordSender;
2840 }
2841
2842 $to = new MailAddress( $this );
2843 $sender = new MailAddress( $from );
2844 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2845 }
2846
2847 /**
2848 * Generate, store, and return a new e-mail confirmation code.
2849 * A hash (unsalted, since it's used as a key) is stored.
2850 *
2851 * @note Call saveSettings() after calling this function to commit
2852 * this change to the database.
2853 *
2854 * @param[out] &$expiration \mixed Accepts the expiration time
2855 * @return \string New token
2856 * @private
2857 */
2858 function confirmationToken( &$expiration ) {
2859 $now = time();
2860 $expires = $now + 7 * 24 * 60 * 60;
2861 $expiration = wfTimestamp( TS_MW, $expires );
2862 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2863 $hash = md5( $token );
2864 $this->load();
2865 $this->mEmailToken = $hash;
2866 $this->mEmailTokenExpires = $expiration;
2867 return $token;
2868 }
2869
2870 /**
2871 * Return a URL the user can use to confirm their email address.
2872 * @param $token \string Accepts the email confirmation token
2873 * @return \string New token URL
2874 * @private
2875 */
2876 function confirmationTokenUrl( $token ) {
2877 return $this->getTokenUrl( 'ConfirmEmail', $token );
2878 }
2879 /**
2880 * Return a URL the user can use to invalidate their email address.
2881 * @param $token \string Accepts the email confirmation token
2882 * @return \string New token URL
2883 * @private
2884 */
2885 function invalidationTokenUrl( $token ) {
2886 return $this->getTokenUrl( 'Invalidateemail', $token );
2887 }
2888
2889 /**
2890 * Internal function to format the e-mail validation/invalidation URLs.
2891 * This uses $wgArticlePath directly as a quickie hack to use the
2892 * hardcoded English names of the Special: pages, for ASCII safety.
2893 *
2894 * @note Since these URLs get dropped directly into emails, using the
2895 * short English names avoids insanely long URL-encoded links, which
2896 * also sometimes can get corrupted in some browsers/mailers
2897 * (bug 6957 with Gmail and Internet Explorer).
2898 *
2899 * @param $page \string Special page
2900 * @param $token \string Token
2901 * @return \string Formatted URL
2902 */
2903 protected function getTokenUrl( $page, $token ) {
2904 global $wgArticlePath;
2905 return wfExpandUrl(
2906 str_replace(
2907 '$1',
2908 "Special:$page/$token",
2909 $wgArticlePath ) );
2910 }
2911
2912 /**
2913 * Mark the e-mail address confirmed.
2914 *
2915 * @note Call saveSettings() after calling this function to commit the change.
2916 */
2917 function confirmEmail() {
2918 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2919 return true;
2920 }
2921
2922 /**
2923 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2924 * address if it was already confirmed.
2925 *
2926 * @note Call saveSettings() after calling this function to commit the change.
2927 */
2928 function invalidateEmail() {
2929 $this->load();
2930 $this->mEmailToken = null;
2931 $this->mEmailTokenExpires = null;
2932 $this->setEmailAuthenticationTimestamp( null );
2933 return true;
2934 }
2935
2936 /**
2937 * Set the e-mail authentication timestamp.
2938 * @param $timestamp \string TS_MW timestamp
2939 */
2940 function setEmailAuthenticationTimestamp( $timestamp ) {
2941 $this->load();
2942 $this->mEmailAuthenticated = $timestamp;
2943 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2944 }
2945
2946 /**
2947 * Is this user allowed to send e-mails within limits of current
2948 * site configuration?
2949 * @return \bool True if allowed
2950 */
2951 function canSendEmail() {
2952 global $wgEnableEmail, $wgEnableUserEmail;
2953 if( !$wgEnableEmail || !$wgEnableUserEmail ) {
2954 return false;
2955 }
2956 $canSend = $this->isEmailConfirmed();
2957 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2958 return $canSend;
2959 }
2960
2961 /**
2962 * Is this user allowed to receive e-mails within limits of current
2963 * site configuration?
2964 * @return \bool True if allowed
2965 */
2966 function canReceiveEmail() {
2967 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2968 }
2969
2970 /**
2971 * Is this user's e-mail address valid-looking and confirmed within
2972 * limits of the current site configuration?
2973 *
2974 * @note If $wgEmailAuthentication is on, this may require the user to have
2975 * confirmed their address by returning a code or using a password
2976 * sent to the address from the wiki.
2977 *
2978 * @return \bool True if confirmed
2979 */
2980 function isEmailConfirmed() {
2981 global $wgEmailAuthentication;
2982 $this->load();
2983 $confirmed = true;
2984 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2985 if( $this->isAnon() )
2986 return false;
2987 if( !self::isValidEmailAddr( $this->mEmail ) )
2988 return false;
2989 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2990 return false;
2991 return true;
2992 } else {
2993 return $confirmed;
2994 }
2995 }
2996
2997 /**
2998 * Check whether there is an outstanding request for e-mail confirmation.
2999 * @return \bool True if pending
3000 */
3001 function isEmailConfirmationPending() {
3002 global $wgEmailAuthentication;
3003 return $wgEmailAuthentication &&
3004 !$this->isEmailConfirmed() &&
3005 $this->mEmailToken &&
3006 $this->mEmailTokenExpires > wfTimestamp();
3007 }
3008
3009 /**
3010 * Get the timestamp of account creation.
3011 *
3012 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3013 * non-existent/anonymous user accounts.
3014 */
3015 public function getRegistration() {
3016 return $this->getId() > 0
3017 ? $this->mRegistration
3018 : false;
3019 }
3020
3021 /**
3022 * Get the timestamp of the first edit
3023 *
3024 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3025 * non-existent/anonymous user accounts.
3026 */
3027 public function getFirstEditTimestamp() {
3028 if( $this->getId() == 0 ) return false; // anons
3029 $dbr = wfGetDB( DB_SLAVE );
3030 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3031 array( 'rev_user' => $this->getId() ),
3032 __METHOD__,
3033 array( 'ORDER BY' => 'rev_timestamp ASC' )
3034 );
3035 if( !$time ) return false; // no edits
3036 return wfTimestamp( TS_MW, $time );
3037 }
3038
3039 /**
3040 * Get the permissions associated with a given list of groups
3041 *
3042 * @param $groups \type{\arrayof{\string}} List of internal group names
3043 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3044 */
3045 static function getGroupPermissions( $groups ) {
3046 global $wgGroupPermissions;
3047 $rights = array();
3048 foreach( $groups as $group ) {
3049 if( isset( $wgGroupPermissions[$group] ) ) {
3050 $rights = array_merge( $rights,
3051 // array_filter removes empty items
3052 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3053 }
3054 }
3055 return array_unique($rights);
3056 }
3057
3058 /**
3059 * Get all the groups who have a given permission
3060 *
3061 * @param $role \string Role to check
3062 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3063 */
3064 static function getGroupsWithPermission( $role ) {
3065 global $wgGroupPermissions;
3066 $allowedGroups = array();
3067 foreach ( $wgGroupPermissions as $group => $rights ) {
3068 if ( isset( $rights[$role] ) && $rights[$role] ) {
3069 $allowedGroups[] = $group;
3070 }
3071 }
3072 return $allowedGroups;
3073 }
3074
3075 /**
3076 * Get the localized descriptive name for a group, if it exists
3077 *
3078 * @param $group \string Internal group name
3079 * @return \string Localized descriptive group name
3080 */
3081 static function getGroupName( $group ) {
3082 global $wgMessageCache;
3083 $wgMessageCache->loadAllMessages();
3084 $key = "group-$group";
3085 $name = wfMsg( $key );
3086 return $name == '' || wfEmptyMsg( $key, $name )
3087 ? $group
3088 : $name;
3089 }
3090
3091 /**
3092 * Get the localized descriptive name for a member of a group, if it exists
3093 *
3094 * @param $group \string Internal group name
3095 * @return \string Localized name for group member
3096 */
3097 static function getGroupMember( $group ) {
3098 global $wgMessageCache;
3099 $wgMessageCache->loadAllMessages();
3100 $key = "group-$group-member";
3101 $name = wfMsg( $key );
3102 return $name == '' || wfEmptyMsg( $key, $name )
3103 ? $group
3104 : $name;
3105 }
3106
3107 /**
3108 * Return the set of defined explicit groups.
3109 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3110 * are not included, as they are defined automatically, not in the database.
3111 * @return \type{\arrayof{\string}} Array of internal group names
3112 */
3113 static function getAllGroups() {
3114 global $wgGroupPermissions;
3115 return array_diff(
3116 array_keys( $wgGroupPermissions ),
3117 self::getImplicitGroups()
3118 );
3119 }
3120
3121 /**
3122 * Get a list of all available permissions.
3123 * @return \type{\arrayof{\string}} Array of permission names
3124 */
3125 static function getAllRights() {
3126 if ( self::$mAllRights === false ) {
3127 global $wgAvailableRights;
3128 if ( count( $wgAvailableRights ) ) {
3129 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3130 } else {
3131 self::$mAllRights = self::$mCoreRights;
3132 }
3133 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3134 }
3135 return self::$mAllRights;
3136 }
3137
3138 /**
3139 * Get a list of implicit groups
3140 * @return \type{\arrayof{\string}} Array of internal group names
3141 */
3142 public static function getImplicitGroups() {
3143 global $wgImplicitGroups;
3144 $groups = $wgImplicitGroups;
3145 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3146 return $groups;
3147 }
3148
3149 /**
3150 * Get the title of a page describing a particular group
3151 *
3152 * @param $group \string Internal group name
3153 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3154 */
3155 static function getGroupPage( $group ) {
3156 global $wgMessageCache;
3157 $wgMessageCache->loadAllMessages();
3158 $page = wfMsgForContent( 'grouppage-' . $group );
3159 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3160 $title = Title::newFromText( $page );
3161 if( is_object( $title ) )
3162 return $title;
3163 }
3164 return false;
3165 }
3166
3167 /**
3168 * Create a link to the group in HTML, if available;
3169 * else return the group name.
3170 *
3171 * @param $group \string Internal name of the group
3172 * @param $text \string The text of the link
3173 * @return \string HTML link to the group
3174 */
3175 static function makeGroupLinkHTML( $group, $text = '' ) {
3176 if( $text == '' ) {
3177 $text = self::getGroupName( $group );
3178 }
3179 $title = self::getGroupPage( $group );
3180 if( $title ) {
3181 global $wgUser;
3182 $sk = $wgUser->getSkin();
3183 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3184 } else {
3185 return $text;
3186 }
3187 }
3188
3189 /**
3190 * Create a link to the group in Wikitext, if available;
3191 * else return the group name.
3192 *
3193 * @param $group \string Internal name of the group
3194 * @param $text \string The text of the link
3195 * @return \string Wikilink to the group
3196 */
3197 static function makeGroupLinkWiki( $group, $text = '' ) {
3198 if( $text == '' ) {
3199 $text = self::getGroupName( $group );
3200 }
3201 $title = self::getGroupPage( $group );
3202 if( $title ) {
3203 $page = $title->getPrefixedText();
3204 return "[[$page|$text]]";
3205 } else {
3206 return $text;
3207 }
3208 }
3209
3210 /**
3211 * Increment the user's edit-count field.
3212 * Will have no effect for anonymous users.
3213 */
3214 function incEditCount() {
3215 if( !$this->isAnon() ) {
3216 $dbw = wfGetDB( DB_MASTER );
3217 $dbw->update( 'user',
3218 array( 'user_editcount=user_editcount+1' ),
3219 array( 'user_id' => $this->getId() ),
3220 __METHOD__ );
3221
3222 // Lazy initialization check...
3223 if( $dbw->affectedRows() == 0 ) {
3224 // Pull from a slave to be less cruel to servers
3225 // Accuracy isn't the point anyway here
3226 $dbr = wfGetDB( DB_SLAVE );
3227 $count = $dbr->selectField( 'revision',
3228 'COUNT(rev_user)',
3229 array( 'rev_user' => $this->getId() ),
3230 __METHOD__ );
3231
3232 // Now here's a goddamn hack...
3233 if( $dbr !== $dbw ) {
3234 // If we actually have a slave server, the count is
3235 // at least one behind because the current transaction
3236 // has not been committed and replicated.
3237 $count++;
3238 } else {
3239 // But if DB_SLAVE is selecting the master, then the
3240 // count we just read includes the revision that was
3241 // just added in the working transaction.
3242 }
3243
3244 $dbw->update( 'user',
3245 array( 'user_editcount' => $count ),
3246 array( 'user_id' => $this->getId() ),
3247 __METHOD__ );
3248 }
3249 }
3250 // edit count in user cache too
3251 $this->invalidateCache();
3252 }
3253
3254 /**
3255 * Get the description of a given right
3256 *
3257 * @param $right \string Right to query
3258 * @return \string Localized description of the right
3259 */
3260 static function getRightDescription( $right ) {
3261 global $wgMessageCache;
3262 $wgMessageCache->loadAllMessages();
3263 $key = "right-$right";
3264 $name = wfMsg( $key );
3265 return $name == '' || wfEmptyMsg( $key, $name )
3266 ? $right
3267 : $name;
3268 }
3269
3270 /**
3271 * Make an old-style password hash
3272 *
3273 * @param $password \string Plain-text password
3274 * @param $userId \string User ID
3275 * @return \string Password hash
3276 */
3277 static function oldCrypt( $password, $userId ) {
3278 global $wgPasswordSalt;
3279 if ( $wgPasswordSalt ) {
3280 return md5( $userId . '-' . md5( $password ) );
3281 } else {
3282 return md5( $password );
3283 }
3284 }
3285
3286 /**
3287 * Make a new-style password hash
3288 *
3289 * @param $password \string Plain-text password
3290 * @param $salt \string Optional salt, may be random or the user ID.
3291 * If unspecified or false, will generate one automatically
3292 * @return \string Password hash
3293 */
3294 static function crypt( $password, $salt = false ) {
3295 global $wgPasswordSalt;
3296
3297 $hash = '';
3298 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3299 return $hash;
3300 }
3301
3302 if( $wgPasswordSalt ) {
3303 if ( $salt === false ) {
3304 $salt = substr( wfGenerateToken(), 0, 8 );
3305 }
3306 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3307 } else {
3308 return ':A:' . md5( $password );
3309 }
3310 }
3311
3312 /**
3313 * Compare a password hash with a plain-text password. Requires the user
3314 * ID if there's a chance that the hash is an old-style hash.
3315 *
3316 * @param $hash \string Password hash
3317 * @param $password \string Plain-text password to compare
3318 * @param $userId \string User ID for old-style password salt
3319 * @return \bool
3320 */
3321 static function comparePasswords( $hash, $password, $userId = false ) {
3322 $m = false;
3323 $type = substr( $hash, 0, 3 );
3324
3325 $result = false;
3326 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3327 return $result;
3328 }
3329
3330 if ( $type == ':A:' ) {
3331 # Unsalted
3332 return md5( $password ) === substr( $hash, 3 );
3333 } elseif ( $type == ':B:' ) {
3334 # Salted
3335 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3336 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3337 } else {
3338 # Old-style
3339 return self::oldCrypt( $password, $userId ) === $hash;
3340 }
3341 }
3342
3343 /**
3344 * Add a newuser log entry for this user
3345 * @param $byEmail Boolean: account made by email?
3346 */
3347 public function addNewUserLogEntry( $byEmail = false ) {
3348 global $wgUser, $wgContLang, $wgNewUserLog;
3349 if( empty($wgNewUserLog) ) {
3350 return true; // disabled
3351 }
3352 $talk = $wgContLang->getFormattedNsText( NS_TALK );
3353 if( $this->getName() == $wgUser->getName() ) {
3354 $action = 'create';
3355 $message = '';
3356 } else {
3357 $action = 'create2';
3358 $message = $byEmail ? wfMsgForContent( 'newuserlog-byemail' ) : '';
3359 }
3360 $log = new LogPage( 'newusers' );
3361 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3362 return true;
3363 }
3364
3365 /**
3366 * Add an autocreate newuser log entry for this user
3367 * Used by things like CentralAuth and perhaps other authplugins.
3368 */
3369 public function addNewUserLogEntryAutoCreate() {
3370 global $wgNewUserLog;
3371 if( empty($wgNewUserLog) ) {
3372 return true; // disabled
3373 }
3374 $log = new LogPage( 'newusers', false );
3375 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3376 return true;
3377 }
3378
3379 }