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