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