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