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