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