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