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