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