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