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