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