Revert r36093 (bug 14404).
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 * @file
5 */
6
7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
9
10 # Serialized record version
11 define( 'MW_USER_VERSION', 6 );
12
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
15
16 /**
17 * Thrown by User::setPassword() on error
18 * @ingroup Exception
19 */
20 class PasswordError extends MWException {
21 // NOP
22 }
23
24 /**
25 * The User object encapsulates all of the user-specific settings (user_id,
26 * name, rights, password, email address, options, last login time). Client
27 * classes use the getXXX() functions to access these fields. These functions
28 * do all the work of determining whether the user is logged in,
29 * whether the requested option can be satisfied from cookies or
30 * whether a database query is needed. Most of the settings needed
31 * for rendering normal pages are set in the cookie to minimize use
32 * of the database.
33 */
34 class User {
35
36 /**
37 * A list of default user toggles, i.e. boolean user preferences that are
38 * displayed by Special:Preferences as checkboxes. This list can be
39 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
40 */
41 static public $mToggles = array(
42 'highlightbroken',
43 'justify',
44 'hideminor',
45 'extendwatchlist',
46 'usenewrc',
47 'numberheadings',
48 'showtoolbar',
49 'editondblclick',
50 'editsection',
51 'editsectiononrightclick',
52 'showtoc',
53 'rememberpassword',
54 'editwidth',
55 'watchcreations',
56 'watchdefault',
57 'watchmoves',
58 'watchdeletion',
59 'minordefault',
60 'previewontop',
61 'previewonfirst',
62 'nocache',
63 'enotifwatchlistpages',
64 'enotifusertalkpages',
65 'enotifminoredits',
66 'enotifrevealaddr',
67 'shownumberswatching',
68 'fancysig',
69 'externaleditor',
70 'externaldiff',
71 'showjumplinks',
72 'uselivepreview',
73 'forceeditsummary',
74 'watchlisthideown',
75 'watchlisthidebots',
76 'watchlisthideminor',
77 'ccmeonemails',
78 'diffonly',
79 'showhiddencats',
80 );
81
82 /**
83 * List of member variables which are saved to the shared cache (memcached).
84 * Any operation which changes the corresponding database fields must
85 * call a cache-clearing function.
86 */
87 static $mCacheVars = array(
88 # user table
89 'mId',
90 'mName',
91 'mRealName',
92 'mPassword',
93 'mNewpassword',
94 'mNewpassTime',
95 'mEmail',
96 'mOptions',
97 'mTouched',
98 'mToken',
99 'mEmailAuthenticated',
100 'mEmailToken',
101 'mEmailTokenExpires',
102 'mRegistration',
103 'mEditCount',
104 # user_group table
105 'mGroups',
106 );
107
108 /**
109 * Core rights
110 * Each of these should have a corresponding message of the form "right-$right"
111 */
112 static $mCoreRights = array(
113 'apihighlimits',
114 'autoconfirmed',
115 'autopatrol',
116 'bigdelete',
117 'block',
118 'blockemail',
119 'bot',
120 'browsearchive',
121 'createaccount',
122 'createpage',
123 'createtalk',
124 'delete',
125 'deletedhistory',
126 'edit',
127 'editinterface',
128 'editusercssjs',
129 'import',
130 'importupload',
131 'ipblock-exempt',
132 'markbotedits',
133 'minoredit',
134 'move',
135 'nominornewtalk',
136 'patrol',
137 'protect',
138 'proxyunbannable',
139 'purge',
140 'read',
141 'reupload',
142 'reupload-shared',
143 'rollback',
144 'suppressredirect',
145 'trackback',
146 'undelete',
147 'unwatchedpages',
148 'upload',
149 'upload_by_url',
150 'userrights',
151 );
152 static $mAllRights = false;
153
154 /**
155 * The cache variable declarations
156 */
157 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
158 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
159 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
160
161 /**
162 * Whether the cache variables have been loaded
163 */
164 var $mDataLoaded;
165
166 /**
167 * Initialisation data source if mDataLoaded==false. May be one of:
168 * defaults anonymous user initialised from class defaults
169 * name initialise from mName
170 * id initialise from mId
171 * session log in from cookies or session if possible
172 *
173 * Use the User::newFrom*() family of functions to set this.
174 */
175 var $mFrom;
176
177 /**
178 * Lazy-initialised variables, invalidated with clearInstanceCache
179 */
180 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
181 $mBlockreason, $mBlock, $mEffectiveGroups;
182
183 /**
184 * Lightweight constructor for anonymous user
185 * Use the User::newFrom* factory functions for other kinds of users
186 */
187 function User() {
188 $this->clearInstanceCache( 'defaults' );
189 }
190
191 /**
192 * Load the user table data for this object from the source given by mFrom
193 */
194 function load() {
195 if ( $this->mDataLoaded ) {
196 return;
197 }
198 wfProfileIn( __METHOD__ );
199
200 # Set it now to avoid infinite recursion in accessors
201 $this->mDataLoaded = true;
202
203 switch ( $this->mFrom ) {
204 case 'defaults':
205 $this->loadDefaults();
206 break;
207 case 'name':
208 $this->mId = self::idFromName( $this->mName );
209 if ( !$this->mId ) {
210 # Nonexistent user placeholder object
211 $this->loadDefaults( $this->mName );
212 } else {
213 $this->loadFromId();
214 }
215 break;
216 case 'id':
217 $this->loadFromId();
218 break;
219 case 'session':
220 $this->loadFromSession();
221 break;
222 default:
223 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
224 }
225 wfProfileOut( __METHOD__ );
226 }
227
228 /**
229 * Load user table data given mId
230 * @return false if the ID does not exist, true otherwise
231 * @private
232 */
233 function loadFromId() {
234 global $wgMemc;
235 if ( $this->mId == 0 ) {
236 $this->loadDefaults();
237 return false;
238 }
239
240 # Try cache
241 $key = wfMemcKey( 'user', 'id', $this->mId );
242 $data = $wgMemc->get( $key );
243 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
244 # Object is expired, load from DB
245 $data = false;
246 }
247
248 if ( !$data ) {
249 wfDebug( "Cache miss for user {$this->mId}\n" );
250 # Load from DB
251 if ( !$this->loadFromDatabase() ) {
252 # Can't load from ID, user is anonymous
253 return false;
254 }
255 $this->saveToCache();
256 } else {
257 wfDebug( "Got user {$this->mId} from cache\n" );
258 # Restore from cache
259 foreach ( self::$mCacheVars as $name ) {
260 $this->$name = $data[$name];
261 }
262 }
263 return true;
264 }
265
266 /**
267 * Save user data to the shared cache
268 */
269 function saveToCache() {
270 $this->load();
271 $this->loadGroups();
272 if ( $this->isAnon() ) {
273 // Anonymous users are uncached
274 return;
275 }
276 $data = array();
277 foreach ( self::$mCacheVars as $name ) {
278 $data[$name] = $this->$name;
279 }
280 $data['mVersion'] = MW_USER_VERSION;
281 $key = wfMemcKey( 'user', 'id', $this->mId );
282 global $wgMemc;
283 $wgMemc->set( $key, $data );
284 }
285
286 /**
287 * Static factory method for creation from username.
288 *
289 * This is slightly less efficient than newFromId(), so use newFromId() if
290 * you have both an ID and a name handy.
291 *
292 * @param string $name Username, validated by Title:newFromText()
293 * @param mixed $validate Validate username. Takes the same parameters as
294 * User::getCanonicalName(), except that true is accepted as an alias
295 * for 'valid', for BC.
296 *
297 * @return User object, or null if the username is invalid. If the username
298 * is not present in the database, the result will be a user object with
299 * a name, zero user ID and default settings.
300 * @static
301 */
302 static function newFromName( $name, $validate = 'valid' ) {
303 if ( $validate === true ) {
304 $validate = 'valid';
305 }
306 $name = self::getCanonicalName( $name, $validate );
307 if ( $name === false ) {
308 return null;
309 } else {
310 # Create unloaded user object
311 $u = new User;
312 $u->mName = $name;
313 $u->mFrom = 'name';
314 return $u;
315 }
316 }
317
318 static function newFromId( $id ) {
319 $u = new User;
320 $u->mId = $id;
321 $u->mFrom = 'id';
322 return $u;
323 }
324
325 /**
326 * Factory method to fetch whichever user has a given email confirmation code.
327 * This code is generated when an account is created or its e-mail address
328 * has changed.
329 *
330 * If the code is invalid or has expired, returns NULL.
331 *
332 * @param string $code
333 * @return User
334 * @static
335 */
336 static function newFromConfirmationCode( $code ) {
337 $dbr = wfGetDB( DB_SLAVE );
338 $id = $dbr->selectField( 'user', 'user_id', array(
339 'user_email_token' => md5( $code ),
340 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
341 ) );
342 if( $id !== false ) {
343 return User::newFromId( $id );
344 } else {
345 return null;
346 }
347 }
348
349 /**
350 * Create a new user object using data from session or cookies. If the
351 * login credentials are invalid, the result is an anonymous user.
352 *
353 * @return User
354 * @static
355 */
356 static function newFromSession() {
357 $user = new User;
358 $user->mFrom = 'session';
359 return $user;
360 }
361
362 /**
363 * Create a new user object from a user row.
364 * The row should have all fields from the user table in it.
365 */
366 static function newFromRow( $row ) {
367 $user = new User;
368 $user->loadFromRow( $row );
369 return $user;
370 }
371
372 /**
373 * Get username given an id.
374 * @param integer $id Database user id
375 * @return string Nickname of a user
376 * @static
377 */
378 static function whoIs( $id ) {
379 $dbr = wfGetDB( DB_SLAVE );
380 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
381 }
382
383 /**
384 * Get the real name of a user given their identifier
385 *
386 * @param int $id Database user id
387 * @return string Real name of a user
388 */
389 static function whoIsReal( $id ) {
390 $dbr = wfGetDB( DB_SLAVE );
391 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
392 }
393
394 /**
395 * Get database id given a user name
396 * @param string $name Nickname of a user
397 * @return integer|null Database user id (null: if non existent
398 * @static
399 */
400 static function idFromName( $name ) {
401 $nt = Title::newFromText( $name );
402 if( is_null( $nt ) ) {
403 # Illegal name
404 return null;
405 }
406 $dbr = wfGetDB( DB_SLAVE );
407 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
408
409 if ( $s === false ) {
410 return 0;
411 } else {
412 return $s->user_id;
413 }
414 }
415
416 /**
417 * Does the string match an anonymous IPv4 address?
418 *
419 * This function exists for username validation, in order to reject
420 * usernames which are similar in form to IP addresses. Strings such
421 * as 300.300.300.300 will return true because it looks like an IP
422 * address, despite not being strictly valid.
423 *
424 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
425 * address because the usemod software would "cloak" anonymous IP
426 * addresses like this, if we allowed accounts like this to be created
427 * new users could get the old edits of these anonymous users.
428 *
429 * @static
430 * @param string $name Nickname of a user
431 * @return bool
432 */
433 static function isIP( $name ) {
434 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name);
435 /*return preg_match("/^
436 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
437 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
438 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
439 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
440 $/x", $name);*/
441 }
442
443 /**
444 * Check if $name is an IPv6 IP.
445 */
446 static function isIPv6($name) {
447 /*
448 * if it has any non-valid characters, it can't be a valid IPv6
449 * address.
450 */
451 if (preg_match("/[^:a-fA-F0-9]/", $name))
452 return false;
453
454 $parts = explode(":", $name);
455 if (count($parts) < 3)
456 return false;
457 foreach ($parts as $part) {
458 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
459 return false;
460 }
461 return true;
462 }
463
464 /**
465 * Is the input a valid username?
466 *
467 * Checks if the input is a valid username, we don't want an empty string,
468 * an IP address, anything that containins slashes (would mess up subpages),
469 * is longer than the maximum allowed username size or doesn't begin with
470 * a capital letter.
471 *
472 * @param string $name
473 * @return bool
474 * @static
475 */
476 static function isValidUserName( $name ) {
477 global $wgContLang, $wgMaxNameChars;
478
479 if ( $name == ''
480 || User::isIP( $name )
481 || strpos( $name, '/' ) !== false
482 || strlen( $name ) > $wgMaxNameChars
483 || $name != $wgContLang->ucfirst( $name ) ) {
484 wfDebugLog( 'username', __METHOD__ .
485 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
486 return false;
487 }
488
489 // Ensure that the name can't be misresolved as a different title,
490 // such as with extra namespace keys at the start.
491 $parsed = Title::newFromText( $name );
492 if( is_null( $parsed )
493 || $parsed->getNamespace()
494 || strcmp( $name, $parsed->getPrefixedText() ) ) {
495 wfDebugLog( 'username', __METHOD__ .
496 ": '$name' invalid due to ambiguous prefixes" );
497 return false;
498 }
499
500 // Check an additional blacklist of troublemaker characters.
501 // Should these be merged into the title char list?
502 $unicodeBlacklist = '/[' .
503 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
504 '\x{00a0}' . # non-breaking space
505 '\x{2000}-\x{200f}' . # various whitespace
506 '\x{2028}-\x{202f}' . # breaks and control chars
507 '\x{3000}' . # ideographic space
508 '\x{e000}-\x{f8ff}' . # private use
509 ']/u';
510 if( preg_match( $unicodeBlacklist, $name ) ) {
511 wfDebugLog( 'username', __METHOD__ .
512 ": '$name' invalid due to blacklisted characters" );
513 return false;
514 }
515
516 return true;
517 }
518
519 /**
520 * Usernames which fail to pass this function will be blocked
521 * from user login and new account registrations, but may be used
522 * internally by batch processes.
523 *
524 * If an account already exists in this form, login will be blocked
525 * by a failure to pass this function.
526 *
527 * @param string $name
528 * @return bool
529 */
530 static function isUsableName( $name ) {
531 global $wgReservedUsernames;
532 return
533 // Must be a valid username, obviously ;)
534 self::isValidUserName( $name ) &&
535
536 // Certain names may be reserved for batch processes.
537 !in_array( $name, $wgReservedUsernames );
538 }
539
540 /**
541 * Usernames which fail to pass this function will be blocked
542 * from new account registrations, but may be used internally
543 * either by batch processes or by user accounts which have
544 * already been created.
545 *
546 * Additional character blacklisting may be added here
547 * rather than in isValidUserName() to avoid disrupting
548 * existing accounts.
549 *
550 * @param string $name
551 * @return bool
552 */
553 static function isCreatableName( $name ) {
554 return
555 self::isUsableName( $name ) &&
556
557 // Registration-time character blacklisting...
558 strpos( $name, '@' ) === false;
559 }
560
561 /**
562 * Is the input a valid password for this user?
563 *
564 * @param string $password Desired password
565 * @return bool
566 */
567 function isValidPassword( $password ) {
568 global $wgMinimalPasswordLength, $wgContLang;
569
570 $result = null;
571 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
572 return $result;
573 if( $result === false )
574 return false;
575
576 // Password needs to be long enough, and can't be the same as the username
577 return strlen( $password ) >= $wgMinimalPasswordLength
578 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
579 }
580
581 /**
582 * Does a string look like an email address?
583 *
584 * There used to be a regular expression here, it got removed because it
585 * rejected valid addresses. Actually just check if there is '@' somewhere
586 * in the given address.
587 *
588 * @todo Check for RFC 2822 compilance (bug 959)
589 *
590 * @param string $addr email address
591 * @return bool
592 */
593 public static function isValidEmailAddr( $addr ) {
594 $result = null;
595 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
596 return $result;
597 }
598
599 return strpos( $addr, '@' ) !== false;
600 }
601
602 /**
603 * Given unvalidated user input, return a canonical username, or false if
604 * the username is invalid.
605 * @param string $name
606 * @param mixed $validate Type of validation to use:
607 * false No validation
608 * 'valid' Valid for batch processes
609 * 'usable' Valid for batch processes and login
610 * 'creatable' Valid for batch processes, login and account creation
611 */
612 static function getCanonicalName( $name, $validate = 'valid' ) {
613 # Force usernames to capital
614 global $wgContLang;
615 $name = $wgContLang->ucfirst( $name );
616
617 # Reject names containing '#'; these will be cleaned up
618 # with title normalisation, but then it's too late to
619 # check elsewhere
620 if( strpos( $name, '#' ) !== false )
621 return false;
622
623 # Clean up name according to title rules
624 $t = Title::newFromText( $name );
625 if( is_null( $t ) ) {
626 return false;
627 }
628
629 # Reject various classes of invalid names
630 $name = $t->getText();
631 global $wgAuth;
632 $name = $wgAuth->getCanonicalName( $t->getText() );
633
634 switch ( $validate ) {
635 case false:
636 break;
637 case 'valid':
638 if ( !User::isValidUserName( $name ) ) {
639 $name = false;
640 }
641 break;
642 case 'usable':
643 if ( !User::isUsableName( $name ) ) {
644 $name = false;
645 }
646 break;
647 case 'creatable':
648 if ( !User::isCreatableName( $name ) ) {
649 $name = false;
650 }
651 break;
652 default:
653 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
654 }
655 return $name;
656 }
657
658 /**
659 * Count the number of edits of a user
660 *
661 * It should not be static and some day should be merged as proper member function / deprecated -- domas
662 *
663 * @param int $uid The user ID to check
664 * @return int
665 * @static
666 */
667 static function edits( $uid ) {
668 wfProfileIn( __METHOD__ );
669 $dbr = wfGetDB( DB_SLAVE );
670 // check if the user_editcount field has been initialized
671 $field = $dbr->selectField(
672 'user', 'user_editcount',
673 array( 'user_id' => $uid ),
674 __METHOD__
675 );
676
677 if( $field === null ) { // it has not been initialized. do so.
678 $dbw = wfGetDB( DB_MASTER );
679 $count = $dbr->selectField(
680 'revision', 'count(*)',
681 array( 'rev_user' => $uid ),
682 __METHOD__
683 );
684 $dbw->update(
685 'user',
686 array( 'user_editcount' => $count ),
687 array( 'user_id' => $uid ),
688 __METHOD__
689 );
690 } else {
691 $count = $field;
692 }
693 wfProfileOut( __METHOD__ );
694 return $count;
695 }
696
697 /**
698 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
699 * @todo hash random numbers to improve security, like generateToken()
700 *
701 * @return string
702 * @static
703 */
704 static function randomPassword() {
705 global $wgMinimalPasswordLength;
706 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
707 $l = strlen( $pwchars ) - 1;
708
709 $pwlength = max( 7, $wgMinimalPasswordLength );
710 $digit = mt_rand(0, $pwlength - 1);
711 $np = '';
712 for ( $i = 0; $i < $pwlength; $i++ ) {
713 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
714 }
715 return $np;
716 }
717
718 /**
719 * Set cached properties to default. Note: this no longer clears
720 * uncached lazy-initialised properties. The constructor does that instead.
721 *
722 * @private
723 */
724 function loadDefaults( $name = false ) {
725 wfProfileIn( __METHOD__ );
726
727 global $wgCookiePrefix;
728
729 $this->mId = 0;
730 $this->mName = $name;
731 $this->mRealName = '';
732 $this->mPassword = $this->mNewpassword = '';
733 $this->mNewpassTime = null;
734 $this->mEmail = '';
735 $this->mOptions = null; # Defer init
736
737 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
738 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
739 } else {
740 $this->mTouched = '0'; # Allow any pages to be cached
741 }
742
743 $this->setToken(); # Random
744 $this->mEmailAuthenticated = null;
745 $this->mEmailToken = '';
746 $this->mEmailTokenExpires = null;
747 $this->mRegistration = wfTimestamp( TS_MW );
748 $this->mGroups = array();
749
750 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
751
752 wfProfileOut( __METHOD__ );
753 }
754
755 /**
756 * Initialise php session
757 * @deprecated use wfSetupSession()
758 */
759 function SetupSession() {
760 wfDeprecated( __METHOD__ );
761 wfSetupSession();
762 }
763
764 /**
765 * Load user data from the session or login cookie. If there are no valid
766 * credentials, initialises the user as an anon.
767 * @return true if the user is logged in, false otherwise
768 */
769 private function loadFromSession() {
770 global $wgMemc, $wgCookiePrefix;
771
772 $result = null;
773 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
774 if ( $result !== null ) {
775 return $result;
776 }
777
778 if ( isset( $_SESSION['wsUserID'] ) ) {
779 if ( 0 != $_SESSION['wsUserID'] ) {
780 $sId = $_SESSION['wsUserID'];
781 } else {
782 $this->loadDefaults();
783 return false;
784 }
785 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
786 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
787 $_SESSION['wsUserID'] = $sId;
788 } else {
789 $this->loadDefaults();
790 return false;
791 }
792 if ( isset( $_SESSION['wsUserName'] ) ) {
793 $sName = $_SESSION['wsUserName'];
794 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
795 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
796 $_SESSION['wsUserName'] = $sName;
797 } else {
798 $this->loadDefaults();
799 return false;
800 }
801
802 $passwordCorrect = FALSE;
803 $this->mId = $sId;
804 if ( !$this->loadFromId() ) {
805 # Not a valid ID, loadFromId has switched the object to anon for us
806 return false;
807 }
808
809 if ( isset( $_SESSION['wsToken'] ) ) {
810 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
811 $from = 'session';
812 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
813 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
814 $from = 'cookie';
815 } else {
816 # No session or persistent login cookie
817 $this->loadDefaults();
818 return false;
819 }
820
821 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
822 $_SESSION['wsToken'] = $this->mToken;
823 wfDebug( "Logged in from $from\n" );
824 return true;
825 } else {
826 # Invalid credentials
827 wfDebug( "Can't log in from $from, invalid credentials\n" );
828 $this->loadDefaults();
829 return false;
830 }
831 }
832
833 /**
834 * Load user and user_group data from the database
835 * $this->mId must be set, this is how the user is identified.
836 *
837 * @return true if the user exists, false if the user is anonymous
838 * @private
839 */
840 function loadFromDatabase() {
841 # Paranoia
842 $this->mId = intval( $this->mId );
843
844 /** Anonymous user */
845 if( !$this->mId ) {
846 $this->loadDefaults();
847 return false;
848 }
849
850 $dbr = wfGetDB( DB_MASTER );
851 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
852
853 if ( $s !== false ) {
854 # Initialise user table data
855 $this->loadFromRow( $s );
856 $this->mGroups = null; // deferred
857 $this->getEditCount(); // revalidation for nulls
858 return true;
859 } else {
860 # Invalid user_id
861 $this->mId = 0;
862 $this->loadDefaults();
863 return false;
864 }
865 }
866
867 /**
868 * Initialise the user object from a row from the user table
869 */
870 function loadFromRow( $row ) {
871 $this->mDataLoaded = true;
872
873 if ( isset( $row->user_id ) ) {
874 $this->mId = $row->user_id;
875 }
876 $this->mName = $row->user_name;
877 $this->mRealName = $row->user_real_name;
878 $this->mPassword = $row->user_password;
879 $this->mNewpassword = $row->user_newpassword;
880 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
881 $this->mEmail = $row->user_email;
882 $this->decodeOptions( $row->user_options );
883 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
884 $this->mToken = $row->user_token;
885 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
886 $this->mEmailToken = $row->user_email_token;
887 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
888 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
889 $this->mEditCount = $row->user_editcount;
890 }
891
892 /**
893 * Load the groups from the database if they aren't already loaded
894 * @private
895 */
896 function loadGroups() {
897 if ( is_null( $this->mGroups ) ) {
898 $dbr = wfGetDB( DB_MASTER );
899 $res = $dbr->select( 'user_groups',
900 array( 'ug_group' ),
901 array( 'ug_user' => $this->mId ),
902 __METHOD__ );
903 $this->mGroups = array();
904 while( $row = $dbr->fetchObject( $res ) ) {
905 $this->mGroups[] = $row->ug_group;
906 }
907 }
908 }
909
910 /**
911 * Clear various cached data stored in this object.
912 * @param string $reloadFrom Reload user and user_groups table data from a
913 * given source. May be "name", "id", "defaults", "session" or false for
914 * no reload.
915 */
916 function clearInstanceCache( $reloadFrom = false ) {
917 $this->mNewtalk = -1;
918 $this->mDatePreference = null;
919 $this->mBlockedby = -1; # Unset
920 $this->mHash = false;
921 $this->mSkin = null;
922 $this->mRights = null;
923 $this->mEffectiveGroups = null;
924
925 if ( $reloadFrom ) {
926 $this->mDataLoaded = false;
927 $this->mFrom = $reloadFrom;
928 }
929 }
930
931 /**
932 * Combine the language default options with any site-specific options
933 * and add the default language variants.
934 * Not really private cause it's called by Language class
935 * @return array
936 * @static
937 * @private
938 */
939 static function getDefaultOptions() {
940 global $wgNamespacesToBeSearchedDefault;
941 /**
942 * Site defaults will override the global/language defaults
943 */
944 global $wgDefaultUserOptions, $wgContLang;
945 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
946
947 /**
948 * default language setting
949 */
950 $variant = $wgContLang->getPreferredVariant( false );
951 $defOpt['variant'] = $variant;
952 $defOpt['language'] = $variant;
953
954 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
955 $defOpt['searchNs'.$nsnum] = $val;
956 }
957 return $defOpt;
958 }
959
960 /**
961 * Get a given default option value.
962 *
963 * @param string $opt
964 * @return string
965 * @static
966 * @public
967 */
968 function getDefaultOption( $opt ) {
969 $defOpts = User::getDefaultOptions();
970 if( isset( $defOpts[$opt] ) ) {
971 return $defOpts[$opt];
972 } else {
973 return '';
974 }
975 }
976
977 /**
978 * Get a list of user toggle names
979 * @return array
980 */
981 static function getToggles() {
982 global $wgContLang;
983 $extraToggles = array();
984 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
985 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
986 }
987
988
989 /**
990 * Get blocking information
991 * @private
992 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
993 * non-critical checks are done against slaves. Check when actually saving should be done against
994 * master.
995 */
996 function getBlockedStatus( $bFromSlave = true ) {
997 global $wgEnableSorbs, $wgProxyWhitelist;
998
999 if ( -1 != $this->mBlockedby ) {
1000 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1001 return;
1002 }
1003
1004 wfProfileIn( __METHOD__ );
1005 wfDebug( __METHOD__.": checking...\n" );
1006
1007 // Initialize data...
1008 // Otherwise something ends up stomping on $this->mBlockedby when
1009 // things get lazy-loaded later, causing false positive block hits
1010 // due to -1 !== 0. Probably session-related... Nothing should be
1011 // overwriting mBlockedby, surely?
1012 $this->load();
1013
1014 $this->mBlockedby = 0;
1015 $this->mHideName = 0;
1016 $ip = wfGetIP();
1017
1018 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1019 # Exempt from all types of IP-block
1020 $ip = '';
1021 }
1022
1023 # User/IP blocking
1024 $this->mBlock = new Block();
1025 $this->mBlock->fromMaster( !$bFromSlave );
1026 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1027 wfDebug( __METHOD__.": Found block.\n" );
1028 $this->mBlockedby = $this->mBlock->mBy;
1029 $this->mBlockreason = $this->mBlock->mReason;
1030 $this->mHideName = $this->mBlock->mHideName;
1031 if ( $this->isLoggedIn() ) {
1032 $this->spreadBlock();
1033 }
1034 } else {
1035 $this->mBlock = null;
1036 wfDebug( __METHOD__.": No block.\n" );
1037 }
1038
1039 # Proxy blocking
1040 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1041 # Local list
1042 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1043 $this->mBlockedby = wfMsg( 'proxyblocker' );
1044 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1045 }
1046
1047 # DNSBL
1048 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1049 if ( $this->inSorbsBlacklist( $ip ) ) {
1050 $this->mBlockedby = wfMsg( 'sorbs' );
1051 $this->mBlockreason = wfMsg( 'sorbsreason' );
1052 }
1053 }
1054 }
1055
1056 # Extensions
1057 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1058
1059 wfProfileOut( __METHOD__ );
1060 }
1061
1062 function inSorbsBlacklist( $ip ) {
1063 global $wgEnableSorbs, $wgSorbsUrl;
1064
1065 return $wgEnableSorbs &&
1066 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1067 }
1068
1069 function inDnsBlacklist( $ip, $base ) {
1070 wfProfileIn( __METHOD__ );
1071
1072 $found = false;
1073 $host = '';
1074 // FIXME: IPv6 ???
1075 $m = array();
1076 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1077 # Make hostname
1078 for ( $i=4; $i>=1; $i-- ) {
1079 $host .= $m[$i] . '.';
1080 }
1081 $host .= $base;
1082
1083 # Send query
1084 $ipList = gethostbynamel( $host );
1085
1086 if ( $ipList ) {
1087 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1088 $found = true;
1089 } else {
1090 wfDebug( "Requested $host, not found in $base.\n" );
1091 }
1092 }
1093
1094 wfProfileOut( __METHOD__ );
1095 return $found;
1096 }
1097
1098 /**
1099 * Is this user subject to rate limiting?
1100 *
1101 * @return bool
1102 */
1103 public function isPingLimitable() {
1104 global $wgRateLimitsExcludedGroups;
1105 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1106 // Deprecated, but kept for backwards-compatibility config
1107 return false;
1108 }
1109 return !$this->isAllowed('noratelimit');
1110 }
1111
1112 /**
1113 * Primitive rate limits: enforce maximum actions per time period
1114 * to put a brake on flooding.
1115 *
1116 * Note: when using a shared cache like memcached, IP-address
1117 * last-hit counters will be shared across wikis.
1118 *
1119 * @return bool true if a rate limiter was tripped
1120 * @public
1121 */
1122 function pingLimiter( $action='edit' ) {
1123
1124 # Call the 'PingLimiter' hook
1125 $result = false;
1126 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1127 return $result;
1128 }
1129
1130 global $wgRateLimits;
1131 if( !isset( $wgRateLimits[$action] ) ) {
1132 return false;
1133 }
1134
1135 # Some groups shouldn't trigger the ping limiter, ever
1136 if( !$this->isPingLimitable() )
1137 return false;
1138
1139 global $wgMemc, $wgRateLimitLog;
1140 wfProfileIn( __METHOD__ );
1141
1142 $limits = $wgRateLimits[$action];
1143 $keys = array();
1144 $id = $this->getId();
1145 $ip = wfGetIP();
1146 $userLimit = false;
1147
1148 if( isset( $limits['anon'] ) && $id == 0 ) {
1149 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1150 }
1151
1152 if( isset( $limits['user'] ) && $id != 0 ) {
1153 $userLimit = $limits['user'];
1154 }
1155 if( $this->isNewbie() ) {
1156 if( isset( $limits['newbie'] ) && $id != 0 ) {
1157 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1158 }
1159 if( isset( $limits['ip'] ) ) {
1160 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1161 }
1162 $matches = array();
1163 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1164 $subnet = $matches[1];
1165 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1166 }
1167 }
1168 // Check for group-specific permissions
1169 // If more than one group applies, use the group with the highest limit
1170 foreach ( $this->getGroups() as $group ) {
1171 if ( isset( $limits[$group] ) ) {
1172 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1173 $userLimit = $limits[$group];
1174 }
1175 }
1176 }
1177 // Set the user limit key
1178 if ( $userLimit !== false ) {
1179 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1180 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1181 }
1182
1183 $triggered = false;
1184 foreach( $keys as $key => $limit ) {
1185 list( $max, $period ) = $limit;
1186 $summary = "(limit $max in {$period}s)";
1187 $count = $wgMemc->get( $key );
1188 if( $count ) {
1189 if( $count > $max ) {
1190 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1191 if( $wgRateLimitLog ) {
1192 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1193 }
1194 $triggered = true;
1195 } else {
1196 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1197 }
1198 } else {
1199 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1200 $wgMemc->add( $key, 1, intval( $period ) );
1201 }
1202 $wgMemc->incr( $key );
1203 }
1204
1205 wfProfileOut( __METHOD__ );
1206 return $triggered;
1207 }
1208
1209 /**
1210 * Check if user is blocked
1211 * @return bool True if blocked, false otherwise
1212 */
1213 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1214 wfDebug( "User::isBlocked: enter\n" );
1215 $this->getBlockedStatus( $bFromSlave );
1216 return $this->mBlockedby !== 0;
1217 }
1218
1219 /**
1220 * Check if user is blocked from editing a particular article
1221 */
1222 function isBlockedFrom( $title, $bFromSlave = false ) {
1223 global $wgBlockAllowsUTEdit;
1224 wfProfileIn( __METHOD__ );
1225 wfDebug( __METHOD__.": enter\n" );
1226
1227 wfDebug( __METHOD__.": asking isBlocked()\n" );
1228 $blocked = $this->isBlocked( $bFromSlave );
1229 # If a user's name is suppressed, they cannot make edits anywhere
1230 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1231 $title->getNamespace() == NS_USER_TALK ) {
1232 $blocked = false;
1233 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1234 }
1235 wfProfileOut( __METHOD__ );
1236 return $blocked;
1237 }
1238
1239 /**
1240 * Get name of blocker
1241 * @return string name of blocker
1242 */
1243 function blockedBy() {
1244 $this->getBlockedStatus();
1245 return $this->mBlockedby;
1246 }
1247
1248 /**
1249 * Get blocking reason
1250 * @return string Blocking reason
1251 */
1252 function blockedFor() {
1253 $this->getBlockedStatus();
1254 return $this->mBlockreason;
1255 }
1256
1257 /**
1258 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1259 */
1260 function getId() {
1261 if( $this->mId === null and $this->mName !== null
1262 and User::isIP( $this->mName ) ) {
1263 // Special case, we know the user is anonymous
1264 return 0;
1265 } elseif( $this->mId === null ) {
1266 // Don't load if this was initialized from an ID
1267 $this->load();
1268 }
1269 return $this->mId;
1270 }
1271
1272 /**
1273 * Set the user and reload all fields according to that ID
1274 */
1275 function setId( $v ) {
1276 $this->mId = $v;
1277 $this->clearInstanceCache( 'id' );
1278 }
1279
1280 /**
1281 * Get the user name, or the IP for anons
1282 */
1283 function getName() {
1284 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1285 # Special case optimisation
1286 return $this->mName;
1287 } else {
1288 $this->load();
1289 if ( $this->mName === false ) {
1290 # Clean up IPs
1291 $this->mName = IP::sanitizeIP( wfGetIP() );
1292 }
1293 return $this->mName;
1294 }
1295 }
1296
1297 /**
1298 * Set the user name.
1299 *
1300 * This does not reload fields from the database according to the given
1301 * name. Rather, it is used to create a temporary "nonexistent user" for
1302 * later addition to the database. It can also be used to set the IP
1303 * address for an anonymous user to something other than the current
1304 * remote IP.
1305 *
1306 * User::newFromName() has rougly the same function, when the named user
1307 * does not exist.
1308 */
1309 function setName( $str ) {
1310 $this->load();
1311 $this->mName = $str;
1312 }
1313
1314 /**
1315 * Return the title dbkey form of the name, for eg user pages.
1316 * @return string
1317 * @public
1318 */
1319 function getTitleKey() {
1320 return str_replace( ' ', '_', $this->getName() );
1321 }
1322
1323 function getNewtalk() {
1324 $this->load();
1325
1326 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1327 if( $this->mNewtalk === -1 ) {
1328 $this->mNewtalk = false; # reset talk page status
1329
1330 # Check memcached separately for anons, who have no
1331 # entire User object stored in there.
1332 if( !$this->mId ) {
1333 global $wgMemc;
1334 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1335 $newtalk = $wgMemc->get( $key );
1336 if( strval( $newtalk ) !== '' ) {
1337 $this->mNewtalk = (bool)$newtalk;
1338 } else {
1339 // Since we are caching this, make sure it is up to date by getting it
1340 // from the master
1341 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1342 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1343 }
1344 } else {
1345 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1346 }
1347 }
1348
1349 return (bool)$this->mNewtalk;
1350 }
1351
1352 /**
1353 * Return the talk page(s) this user has new messages on.
1354 */
1355 function getNewMessageLinks() {
1356 $talks = array();
1357 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1358 return $talks;
1359
1360 if (!$this->getNewtalk())
1361 return array();
1362 $up = $this->getUserPage();
1363 $utp = $up->getTalkPage();
1364 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1365 }
1366
1367
1368 /**
1369 * Perform a user_newtalk check, uncached.
1370 * Use getNewtalk for a cached check.
1371 *
1372 * @param string $field
1373 * @param mixed $id
1374 * @param bool $fromMaster True to fetch from the master, false for a slave
1375 * @return bool
1376 * @private
1377 */
1378 function checkNewtalk( $field, $id, $fromMaster = false ) {
1379 if ( $fromMaster ) {
1380 $db = wfGetDB( DB_MASTER );
1381 } else {
1382 $db = wfGetDB( DB_SLAVE );
1383 }
1384 $ok = $db->selectField( 'user_newtalk', $field,
1385 array( $field => $id ), __METHOD__ );
1386 return $ok !== false;
1387 }
1388
1389 /**
1390 * Add or update the
1391 * @param string $field
1392 * @param mixed $id
1393 * @private
1394 */
1395 function updateNewtalk( $field, $id ) {
1396 $dbw = wfGetDB( DB_MASTER );
1397 $dbw->insert( 'user_newtalk',
1398 array( $field => $id ),
1399 __METHOD__,
1400 'IGNORE' );
1401 if ( $dbw->affectedRows() ) {
1402 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1403 return true;
1404 } else {
1405 wfDebug( __METHOD__." already set ($field, $id)\n" );
1406 return false;
1407 }
1408 }
1409
1410 /**
1411 * Clear the new messages flag for the given user
1412 * @param string $field
1413 * @param mixed $id
1414 * @private
1415 */
1416 function deleteNewtalk( $field, $id ) {
1417 $dbw = wfGetDB( DB_MASTER );
1418 $dbw->delete( 'user_newtalk',
1419 array( $field => $id ),
1420 __METHOD__ );
1421 if ( $dbw->affectedRows() ) {
1422 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1423 return true;
1424 } else {
1425 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1426 return false;
1427 }
1428 }
1429
1430 /**
1431 * Update the 'You have new messages!' status.
1432 * @param bool $val
1433 */
1434 function setNewtalk( $val ) {
1435 if( wfReadOnly() ) {
1436 return;
1437 }
1438
1439 $this->load();
1440 $this->mNewtalk = $val;
1441
1442 if( $this->isAnon() ) {
1443 $field = 'user_ip';
1444 $id = $this->getName();
1445 } else {
1446 $field = 'user_id';
1447 $id = $this->getId();
1448 }
1449 global $wgMemc;
1450
1451 if( $val ) {
1452 $changed = $this->updateNewtalk( $field, $id );
1453 } else {
1454 $changed = $this->deleteNewtalk( $field, $id );
1455 }
1456
1457 if( $this->isAnon() ) {
1458 // Anons have a separate memcached space, since
1459 // user records aren't kept for them.
1460 $key = wfMemcKey( 'newtalk', 'ip', $id );
1461 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1462 }
1463 if ( $changed ) {
1464 $this->invalidateCache();
1465 }
1466 }
1467
1468 /**
1469 * Generate a current or new-future timestamp to be stored in the
1470 * user_touched field when we update things.
1471 */
1472 private static function newTouchedTimestamp() {
1473 global $wgClockSkewFudge;
1474 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1475 }
1476
1477 /**
1478 * Clear user data from memcached.
1479 * Use after applying fun updates to the database; caller's
1480 * responsibility to update user_touched if appropriate.
1481 *
1482 * Called implicitly from invalidateCache() and saveSettings().
1483 */
1484 private function clearSharedCache() {
1485 if( $this->mId ) {
1486 global $wgMemc;
1487 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1488 }
1489 }
1490
1491 /**
1492 * Immediately touch the user data cache for this account.
1493 * Updates user_touched field, and removes account data from memcached
1494 * for reload on the next hit.
1495 */
1496 function invalidateCache() {
1497 $this->load();
1498 if( $this->mId ) {
1499 $this->mTouched = self::newTouchedTimestamp();
1500
1501 $dbw = wfGetDB( DB_MASTER );
1502 $dbw->update( 'user',
1503 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1504 array( 'user_id' => $this->mId ),
1505 __METHOD__ );
1506
1507 $this->clearSharedCache();
1508 }
1509 }
1510
1511 function validateCache( $timestamp ) {
1512 $this->load();
1513 return ($timestamp >= $this->mTouched);
1514 }
1515
1516 /**
1517 * Set the password and reset the random token
1518 * Calls through to authentication plugin if necessary;
1519 * will have no effect if the auth plugin refuses to
1520 * pass the change through or if the legal password
1521 * checks fail.
1522 *
1523 * As a special case, setting the password to null
1524 * wipes it, so the account cannot be logged in until
1525 * a new password is set, for instance via e-mail.
1526 *
1527 * @param string $str
1528 * @throws PasswordError on failure
1529 */
1530 function setPassword( $str ) {
1531 global $wgAuth;
1532
1533 if( $str !== null ) {
1534 if( !$wgAuth->allowPasswordChange() ) {
1535 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1536 }
1537
1538 if( !$this->isValidPassword( $str ) ) {
1539 global $wgMinimalPasswordLength;
1540 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1541 $wgMinimalPasswordLength ) );
1542 }
1543 }
1544
1545 if( !$wgAuth->setPassword( $this, $str ) ) {
1546 throw new PasswordError( wfMsg( 'externaldberror' ) );
1547 }
1548
1549 $this->setInternalPassword( $str );
1550
1551 return true;
1552 }
1553
1554 /**
1555 * Set the password and reset the random token no matter
1556 * what.
1557 *
1558 * @param string $str
1559 */
1560 function setInternalPassword( $str ) {
1561 $this->load();
1562 $this->setToken();
1563
1564 if( $str === null ) {
1565 // Save an invalid hash...
1566 $this->mPassword = '';
1567 } else {
1568 $this->mPassword = self::crypt( $str );
1569 }
1570 $this->mNewpassword = '';
1571 $this->mNewpassTime = null;
1572 }
1573
1574 function getToken() {
1575 $this->load();
1576 return $this->mToken;
1577 }
1578
1579 /**
1580 * Set the random token (used for persistent authentication)
1581 * Called from loadDefaults() among other places.
1582 * @private
1583 */
1584 function setToken( $token = false ) {
1585 global $wgSecretKey, $wgProxyKey;
1586 $this->load();
1587 if ( !$token ) {
1588 if ( $wgSecretKey ) {
1589 $key = $wgSecretKey;
1590 } elseif ( $wgProxyKey ) {
1591 $key = $wgProxyKey;
1592 } else {
1593 $key = microtime();
1594 }
1595 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1596 } else {
1597 $this->mToken = $token;
1598 }
1599 }
1600
1601 function setCookiePassword( $str ) {
1602 $this->load();
1603 $this->mCookiePassword = md5( $str );
1604 }
1605
1606 /**
1607 * Set the password for a password reminder or new account email
1608 * Sets the user_newpass_time field if $throttle is true
1609 */
1610 function setNewpassword( $str, $throttle = true ) {
1611 $this->load();
1612 $this->mNewpassword = self::crypt( $str );
1613 if ( $throttle ) {
1614 $this->mNewpassTime = wfTimestampNow();
1615 }
1616 }
1617
1618 /**
1619 * Returns true if a password reminder email has already been sent within
1620 * the last $wgPasswordReminderResendTime hours
1621 */
1622 function isPasswordReminderThrottled() {
1623 global $wgPasswordReminderResendTime;
1624 $this->load();
1625 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1626 return false;
1627 }
1628 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1629 return time() < $expiry;
1630 }
1631
1632 function getEmail() {
1633 $this->load();
1634 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1635 return $this->mEmail;
1636 }
1637
1638 function getEmailAuthenticationTimestamp() {
1639 $this->load();
1640 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1641 return $this->mEmailAuthenticated;
1642 }
1643
1644 function setEmail( $str ) {
1645 $this->load();
1646 $this->mEmail = $str;
1647 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1648 }
1649
1650 function getRealName() {
1651 $this->load();
1652 return $this->mRealName;
1653 }
1654
1655 function setRealName( $str ) {
1656 $this->load();
1657 $this->mRealName = $str;
1658 }
1659
1660 /**
1661 * @param string $oname The option to check
1662 * @param string $defaultOverride A default value returned if the option does not exist
1663 * @return string
1664 */
1665 function getOption( $oname, $defaultOverride = '' ) {
1666 $this->load();
1667
1668 if ( is_null( $this->mOptions ) ) {
1669 if($defaultOverride != '') {
1670 return $defaultOverride;
1671 }
1672 $this->mOptions = User::getDefaultOptions();
1673 }
1674
1675 if ( array_key_exists( $oname, $this->mOptions ) ) {
1676 return trim( $this->mOptions[$oname] );
1677 } else {
1678 return $defaultOverride;
1679 }
1680 }
1681
1682 /**
1683 * Get the user's date preference, including some important migration for
1684 * old user rows.
1685 */
1686 function getDatePreference() {
1687 if ( is_null( $this->mDatePreference ) ) {
1688 global $wgLang;
1689 $value = $this->getOption( 'date' );
1690 $map = $wgLang->getDatePreferenceMigrationMap();
1691 if ( isset( $map[$value] ) ) {
1692 $value = $map[$value];
1693 }
1694 $this->mDatePreference = $value;
1695 }
1696 return $this->mDatePreference;
1697 }
1698
1699 /**
1700 * @param string $oname The option to check
1701 * @return bool False if the option is not selected, true if it is
1702 */
1703 function getBoolOption( $oname ) {
1704 return (bool)$this->getOption( $oname );
1705 }
1706
1707 /**
1708 * Get an option as an integer value from the source string.
1709 * @param string $oname The option to check
1710 * @param int $default Optional value to return if option is unset/blank.
1711 * @return int
1712 */
1713 function getIntOption( $oname, $default=0 ) {
1714 $val = $this->getOption( $oname );
1715 if( $val == '' ) {
1716 $val = $default;
1717 }
1718 return intval( $val );
1719 }
1720
1721 function setOption( $oname, $val ) {
1722 $this->load();
1723 if ( is_null( $this->mOptions ) ) {
1724 $this->mOptions = User::getDefaultOptions();
1725 }
1726 if ( $oname == 'skin' ) {
1727 # Clear cached skin, so the new one displays immediately in Special:Preferences
1728 unset( $this->mSkin );
1729 }
1730 // Filter out any newlines that may have passed through input validation.
1731 // Newlines are used to separate items in the options blob.
1732 if( $val ) {
1733 $val = str_replace( "\r\n", "\n", $val );
1734 $val = str_replace( "\r", "\n", $val );
1735 $val = str_replace( "\n", " ", $val );
1736 }
1737 // Explicitly NULL values should refer to defaults
1738 global $wgDefaultUserOptions;
1739 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1740 $val = $wgDefaultUserOptions[$oname];
1741 }
1742 $this->mOptions[$oname] = $val;
1743 }
1744
1745 function getRights() {
1746 if ( is_null( $this->mRights ) ) {
1747 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1748 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1749 // Force reindexation of rights when a hook has unset one of them
1750 $this->mRights = array_values( $this->mRights );
1751 }
1752 return $this->mRights;
1753 }
1754
1755 /**
1756 * Get the list of explicit group memberships this user has.
1757 * The implicit * and user groups are not included.
1758 * @return array of strings
1759 */
1760 function getGroups() {
1761 $this->load();
1762 return $this->mGroups;
1763 }
1764
1765 /**
1766 * Get the list of implicit group memberships this user has.
1767 * This includes all explicit groups, plus 'user' if logged in,
1768 * '*' for all accounts and autopromoted groups
1769 * @param boolean $recache Don't use the cache
1770 * @return array of strings
1771 */
1772 function getEffectiveGroups( $recache = false ) {
1773 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1774 $this->mEffectiveGroups = $this->getGroups();
1775 $this->mEffectiveGroups[] = '*';
1776 if( $this->getId() ) {
1777 $this->mEffectiveGroups[] = 'user';
1778
1779 $this->mEffectiveGroups = array_unique( array_merge(
1780 $this->mEffectiveGroups,
1781 Autopromote::getAutopromoteGroups( $this )
1782 ) );
1783
1784 # Hook for additional groups
1785 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1786 }
1787 }
1788 return $this->mEffectiveGroups;
1789 }
1790
1791 /* Return the edit count for the user. This is where User::edits should have been */
1792 function getEditCount() {
1793 if ($this->mId) {
1794 if ( !isset( $this->mEditCount ) ) {
1795 /* Populate the count, if it has not been populated yet */
1796 $this->mEditCount = User::edits($this->mId);
1797 }
1798 return $this->mEditCount;
1799 } else {
1800 /* nil */
1801 return null;
1802 }
1803 }
1804
1805 /**
1806 * Add the user to the given group.
1807 * This takes immediate effect.
1808 * @param string $group
1809 */
1810 function addGroup( $group ) {
1811 $dbw = wfGetDB( DB_MASTER );
1812 if( $this->getId() ) {
1813 $dbw->insert( 'user_groups',
1814 array(
1815 'ug_user' => $this->getID(),
1816 'ug_group' => $group,
1817 ),
1818 'User::addGroup',
1819 array( 'IGNORE' ) );
1820 }
1821
1822 $this->loadGroups();
1823 $this->mGroups[] = $group;
1824 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1825
1826 $this->invalidateCache();
1827 }
1828
1829 /**
1830 * Remove the user from the given group.
1831 * This takes immediate effect.
1832 * @param string $group
1833 */
1834 function removeGroup( $group ) {
1835 $this->load();
1836 $dbw = wfGetDB( DB_MASTER );
1837 $dbw->delete( 'user_groups',
1838 array(
1839 'ug_user' => $this->getID(),
1840 'ug_group' => $group,
1841 ),
1842 'User::removeGroup' );
1843
1844 $this->loadGroups();
1845 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1846 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1847
1848 $this->invalidateCache();
1849 }
1850
1851
1852 /**
1853 * A more legible check for non-anonymousness.
1854 * Returns true if the user is not an anonymous visitor.
1855 *
1856 * @return bool
1857 */
1858 function isLoggedIn() {
1859 return $this->getID() != 0;
1860 }
1861
1862 /**
1863 * A more legible check for anonymousness.
1864 * Returns true if the user is an anonymous visitor.
1865 *
1866 * @return bool
1867 */
1868 function isAnon() {
1869 return !$this->isLoggedIn();
1870 }
1871
1872 /**
1873 * Whether the user is a bot
1874 * @deprecated
1875 */
1876 function isBot() {
1877 wfDeprecated( __METHOD__ );
1878 return $this->isAllowed( 'bot' );
1879 }
1880
1881 /**
1882 * Check if user is allowed to access a feature / make an action
1883 * @param string $action Action to be checked
1884 * @return boolean True: action is allowed, False: action should not be allowed
1885 */
1886 function isAllowed($action='') {
1887 if ( $action === '' )
1888 // In the spirit of DWIM
1889 return true;
1890
1891 return in_array( $action, $this->getRights() );
1892 }
1893
1894 /**
1895 * Check whether to enable recent changes patrol features for this user
1896 * @return bool
1897 */
1898 public function useRCPatrol() {
1899 global $wgUseRCPatrol;
1900 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1901 }
1902
1903 /**
1904 * Check whether to enable recent changes patrol features for this user
1905 * @return bool
1906 */
1907 public function useNPPatrol() {
1908 global $wgUseRCPatrol, $wgUseNPPatrol;
1909 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1910 }
1911
1912 /**
1913 * Load a skin if it doesn't exist or return it
1914 * @todo FIXME : need to check the old failback system [AV]
1915 */
1916 function &getSkin() {
1917 global $wgRequest;
1918 if ( ! isset( $this->mSkin ) ) {
1919 wfProfileIn( __METHOD__ );
1920
1921 # get the user skin
1922 $userSkin = $this->getOption( 'skin' );
1923 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1924
1925 $this->mSkin =& Skin::newFromKey( $userSkin );
1926 wfProfileOut( __METHOD__ );
1927 }
1928 return $this->mSkin;
1929 }
1930
1931 /**#@+
1932 * @param string $title Article title to look at
1933 */
1934
1935 /**
1936 * Check watched status of an article
1937 * @return bool True if article is watched
1938 */
1939 function isWatched( $title ) {
1940 $wl = WatchedItem::fromUserTitle( $this, $title );
1941 return $wl->isWatched();
1942 }
1943
1944 /**
1945 * Watch an article
1946 */
1947 function addWatch( $title ) {
1948 $wl = WatchedItem::fromUserTitle( $this, $title );
1949 $wl->addWatch();
1950 $this->invalidateCache();
1951 }
1952
1953 /**
1954 * Stop watching an article
1955 */
1956 function removeWatch( $title ) {
1957 $wl = WatchedItem::fromUserTitle( $this, $title );
1958 $wl->removeWatch();
1959 $this->invalidateCache();
1960 }
1961
1962 /**
1963 * Clear the user's notification timestamp for the given title.
1964 * If e-notif e-mails are on, they will receive notification mails on
1965 * the next change of the page if it's watched etc.
1966 */
1967 function clearNotification( &$title ) {
1968 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1969
1970 # Do nothing if the database is locked to writes
1971 if( wfReadOnly() ) {
1972 return;
1973 }
1974
1975 if ($title->getNamespace() == NS_USER_TALK &&
1976 $title->getText() == $this->getName() ) {
1977 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1978 return;
1979 $this->setNewtalk( false );
1980 }
1981
1982 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1983 return;
1984 }
1985
1986 if( $this->isAnon() ) {
1987 // Nothing else to do...
1988 return;
1989 }
1990
1991 // Only update the timestamp if the page is being watched.
1992 // The query to find out if it is watched is cached both in memcached and per-invocation,
1993 // and when it does have to be executed, it can be on a slave
1994 // If this is the user's newtalk page, we always update the timestamp
1995 if ($title->getNamespace() == NS_USER_TALK &&
1996 $title->getText() == $wgUser->getName())
1997 {
1998 $watched = true;
1999 } elseif ( $this->getId() == $wgUser->getId() ) {
2000 $watched = $title->userIsWatching();
2001 } else {
2002 $watched = true;
2003 }
2004
2005 // If the page is watched by the user (or may be watched), update the timestamp on any
2006 // any matching rows
2007 if ( $watched ) {
2008 $dbw = wfGetDB( DB_MASTER );
2009 $dbw->update( 'watchlist',
2010 array( /* SET */
2011 'wl_notificationtimestamp' => NULL
2012 ), array( /* WHERE */
2013 'wl_title' => $title->getDBkey(),
2014 'wl_namespace' => $title->getNamespace(),
2015 'wl_user' => $this->getID()
2016 ), 'User::clearLastVisited'
2017 );
2018 }
2019 }
2020
2021 /**#@-*/
2022
2023 /**
2024 * Resets all of the given user's page-change notification timestamps.
2025 * If e-notif e-mails are on, they will receive notification mails on
2026 * the next change of any watched page.
2027 *
2028 * @param int $currentUser user ID number
2029 * @public
2030 */
2031 function clearAllNotifications( $currentUser ) {
2032 global $wgUseEnotif, $wgShowUpdatedMarker;
2033 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2034 $this->setNewtalk( false );
2035 return;
2036 }
2037 if( $currentUser != 0 ) {
2038 $dbw = wfGetDB( DB_MASTER );
2039 $dbw->update( 'watchlist',
2040 array( /* SET */
2041 'wl_notificationtimestamp' => NULL
2042 ), array( /* WHERE */
2043 'wl_user' => $currentUser
2044 ), __METHOD__
2045 );
2046 # We also need to clear here the "you have new message" notification for the own user_talk page
2047 # This is cleared one page view later in Article::viewUpdates();
2048 }
2049 }
2050
2051 /**
2052 * @private
2053 * @return string Encoding options
2054 */
2055 function encodeOptions() {
2056 $this->load();
2057 if ( is_null( $this->mOptions ) ) {
2058 $this->mOptions = User::getDefaultOptions();
2059 }
2060 $a = array();
2061 foreach ( $this->mOptions as $oname => $oval ) {
2062 array_push( $a, $oname.'='.$oval );
2063 }
2064 $s = implode( "\n", $a );
2065 return $s;
2066 }
2067
2068 /**
2069 * @private
2070 */
2071 function decodeOptions( $str ) {
2072 $this->mOptions = array();
2073 $a = explode( "\n", $str );
2074 foreach ( $a as $s ) {
2075 $m = array();
2076 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2077 $this->mOptions[$m[1]] = $m[2];
2078 }
2079 }
2080 }
2081
2082 protected function setCookie( $name, $value, $exp=0 ) {
2083 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2084 if( $exp == 0 ) {
2085 $exp = time() + $wgCookieExpiration;
2086 }
2087 $httpOnlySafe = wfHttpOnlySafe();
2088 wfDebugLog( 'cookie',
2089 'setcookie: "' . implode( '", "',
2090 array(
2091 $wgCookiePrefix . $name,
2092 $value,
2093 $exp,
2094 '/',
2095 $wgCookieDomain,
2096 $wgCookieSecure,
2097 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2098 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2099 setcookie( $wgCookiePrefix . $name,
2100 $value,
2101 $exp,
2102 '/',
2103 $wgCookieDomain,
2104 $wgCookieSecure,
2105 $wgCookieHttpOnly );
2106 } else {
2107 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2108 // stab stab!
2109 setcookie( $wgCookiePrefix . $name,
2110 $value,
2111 $exp,
2112 '/',
2113 $wgCookieDomain,
2114 $wgCookieSecure );
2115 }
2116 }
2117
2118 protected function clearCookie( $name ) {
2119 $this->setCookie( $name, '', time() - 86400 );
2120 }
2121
2122 function setCookies() {
2123 $this->load();
2124 if ( 0 == $this->mId ) return;
2125 $session = array(
2126 'wsUserID' => $this->mId,
2127 'wsToken' => $this->mToken,
2128 'wsUserName' => $this->getName()
2129 );
2130 $cookies = array(
2131 'UserID' => $this->mId,
2132 'UserName' => $this->getName(),
2133 );
2134 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2135 $cookies['Token'] = $this->mToken;
2136 } else {
2137 $cookies['Token'] = false;
2138 }
2139
2140 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2141 $_SESSION = $session + $_SESSION;
2142 foreach ( $cookies as $name => $value ) {
2143 if ( $value === false ) {
2144 $this->clearCookie( $name );
2145 } else {
2146 $this->setCookie( $name, $value );
2147 }
2148 }
2149 }
2150
2151 /**
2152 * Logout user.
2153 */
2154 function logout() {
2155 global $wgUser;
2156 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2157 $this->doLogout();
2158 }
2159 }
2160
2161 /**
2162 * Really logout user
2163 * Clears the cookies and session, resets the instance cache
2164 */
2165 function doLogout() {
2166 $this->clearInstanceCache( 'defaults' );
2167
2168 $_SESSION['wsUserID'] = 0;
2169
2170 $this->clearCookie( 'UserID' );
2171 $this->clearCookie( 'Token' );
2172
2173 # Remember when user logged out, to prevent seeing cached pages
2174 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2175 }
2176
2177 /**
2178 * Save object settings into database
2179 * @todo Only rarely do all these fields need to be set!
2180 */
2181 function saveSettings() {
2182 $this->load();
2183 if ( wfReadOnly() ) { return; }
2184 if ( 0 == $this->mId ) { return; }
2185
2186 $this->mTouched = self::newTouchedTimestamp();
2187
2188 $dbw = wfGetDB( DB_MASTER );
2189 $dbw->update( 'user',
2190 array( /* SET */
2191 'user_name' => $this->mName,
2192 'user_password' => $this->mPassword,
2193 'user_newpassword' => $this->mNewpassword,
2194 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2195 'user_real_name' => $this->mRealName,
2196 'user_email' => $this->mEmail,
2197 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2198 'user_options' => $this->encodeOptions(),
2199 'user_touched' => $dbw->timestamp($this->mTouched),
2200 'user_token' => $this->mToken,
2201 'user_email_token' => $this->mEmailToken,
2202 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2203 ), array( /* WHERE */
2204 'user_id' => $this->mId
2205 ), __METHOD__
2206 );
2207 wfRunHooks( 'UserSaveSettings', array( $this ) );
2208 $this->clearSharedCache();
2209 }
2210
2211 /**
2212 * Checks if a user with the given name exists, returns the ID.
2213 */
2214 function idForName() {
2215 $s = trim( $this->getName() );
2216 if ( $s === '' ) return 0;
2217
2218 $dbr = wfGetDB( DB_SLAVE );
2219 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2220 if ( $id === false ) {
2221 $id = 0;
2222 }
2223 return $id;
2224 }
2225
2226 /**
2227 * Add a user to the database, return the user object
2228 *
2229 * @param string $name The user's name
2230 * @param array $params Associative array of non-default parameters to save to the database:
2231 * password The user's password. Password logins will be disabled if this is omitted.
2232 * newpassword A temporary password mailed to the user
2233 * email The user's email address
2234 * email_authenticated The email authentication timestamp
2235 * real_name The user's real name
2236 * options An associative array of non-default options
2237 * token Random authentication token. Do not set.
2238 * registration Registration timestamp. Do not set.
2239 *
2240 * @return User object, or null if the username already exists
2241 */
2242 static function createNew( $name, $params = array() ) {
2243 $user = new User;
2244 $user->load();
2245 if ( isset( $params['options'] ) ) {
2246 $user->mOptions = $params['options'] + $user->mOptions;
2247 unset( $params['options'] );
2248 }
2249 $dbw = wfGetDB( DB_MASTER );
2250 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2251 $fields = array(
2252 'user_id' => $seqVal,
2253 'user_name' => $name,
2254 'user_password' => $user->mPassword,
2255 'user_newpassword' => $user->mNewpassword,
2256 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2257 'user_email' => $user->mEmail,
2258 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2259 'user_real_name' => $user->mRealName,
2260 'user_options' => $user->encodeOptions(),
2261 'user_token' => $user->mToken,
2262 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2263 'user_editcount' => 0,
2264 );
2265 foreach ( $params as $name => $value ) {
2266 $fields["user_$name"] = $value;
2267 }
2268 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2269 if ( $dbw->affectedRows() ) {
2270 $newUser = User::newFromId( $dbw->insertId() );
2271 } else {
2272 $newUser = null;
2273 }
2274 return $newUser;
2275 }
2276
2277 /**
2278 * Add an existing user object to the database
2279 */
2280 function addToDatabase() {
2281 $this->load();
2282 $dbw = wfGetDB( DB_MASTER );
2283 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2284 $dbw->insert( 'user',
2285 array(
2286 'user_id' => $seqVal,
2287 'user_name' => $this->mName,
2288 'user_password' => $this->mPassword,
2289 'user_newpassword' => $this->mNewpassword,
2290 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2291 'user_email' => $this->mEmail,
2292 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2293 'user_real_name' => $this->mRealName,
2294 'user_options' => $this->encodeOptions(),
2295 'user_token' => $this->mToken,
2296 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2297 'user_editcount' => 0,
2298 ), __METHOD__
2299 );
2300 $this->mId = $dbw->insertId();
2301
2302 # Clear instance cache other than user table data, which is already accurate
2303 $this->clearInstanceCache();
2304 }
2305
2306 /**
2307 * If the (non-anonymous) user is blocked, this function will block any IP address
2308 * that they successfully log on from.
2309 */
2310 function spreadBlock() {
2311 wfDebug( __METHOD__."()\n" );
2312 $this->load();
2313 if ( $this->mId == 0 ) {
2314 return;
2315 }
2316
2317 $userblock = Block::newFromDB( '', $this->mId );
2318 if ( !$userblock ) {
2319 return;
2320 }
2321
2322 $userblock->doAutoblock( wfGetIp() );
2323
2324 }
2325
2326 /**
2327 * Generate a string which will be different for any combination of
2328 * user options which would produce different parser output.
2329 * This will be used as part of the hash key for the parser cache,
2330 * so users will the same options can share the same cached data
2331 * safely.
2332 *
2333 * Extensions which require it should install 'PageRenderingHash' hook,
2334 * which will give them a chance to modify this key based on their own
2335 * settings.
2336 *
2337 * @return string
2338 */
2339 function getPageRenderingHash() {
2340 global $wgContLang, $wgUseDynamicDates, $wgLang;
2341 if( $this->mHash ){
2342 return $this->mHash;
2343 }
2344
2345 // stubthreshold is only included below for completeness,
2346 // it will always be 0 when this function is called by parsercache.
2347
2348 $confstr = $this->getOption( 'math' );
2349 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2350 if ( $wgUseDynamicDates ) {
2351 $confstr .= '!' . $this->getDatePreference();
2352 }
2353 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2354 $confstr .= '!' . $wgLang->getCode();
2355 $confstr .= '!' . $this->getOption( 'thumbsize' );
2356 // add in language specific options, if any
2357 $extra = $wgContLang->getExtraHashOptions();
2358 $confstr .= $extra;
2359
2360 // Give a chance for extensions to modify the hash, if they have
2361 // extra options or other effects on the parser cache.
2362 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2363
2364 // Make it a valid memcached key fragment
2365 $confstr = str_replace( ' ', '_', $confstr );
2366 $this->mHash = $confstr;
2367 return $confstr;
2368 }
2369
2370 function isBlockedFromCreateAccount() {
2371 $this->getBlockedStatus();
2372 return $this->mBlock && $this->mBlock->mCreateAccount;
2373 }
2374
2375 /**
2376 * Determine if the user is blocked from using Special:Emailuser.
2377 *
2378 * @public
2379 * @return boolean
2380 */
2381 function isBlockedFromEmailuser() {
2382 $this->getBlockedStatus();
2383 return $this->mBlock && $this->mBlock->mBlockEmail;
2384 }
2385
2386 function isAllowedToCreateAccount() {
2387 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2388 }
2389
2390 /**
2391 * @deprecated
2392 */
2393 function setLoaded( $loaded ) {
2394 wfDeprecated( __METHOD__ );
2395 }
2396
2397 /**
2398 * Get this user's personal page title.
2399 *
2400 * @return Title
2401 * @public
2402 */
2403 function getUserPage() {
2404 return Title::makeTitle( NS_USER, $this->getName() );
2405 }
2406
2407 /**
2408 * Get this user's talk page title.
2409 *
2410 * @return Title
2411 * @public
2412 */
2413 function getTalkPage() {
2414 $title = $this->getUserPage();
2415 return $title->getTalkPage();
2416 }
2417
2418 /**
2419 * @static
2420 */
2421 function getMaxID() {
2422 static $res; // cache
2423
2424 if ( isset( $res ) )
2425 return $res;
2426 else {
2427 $dbr = wfGetDB( DB_SLAVE );
2428 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2429 }
2430 }
2431
2432 /**
2433 * Determine whether the user is a newbie. Newbies are either
2434 * anonymous IPs, or the most recently created accounts.
2435 * @return bool True if it is a newbie.
2436 */
2437 function isNewbie() {
2438 return !$this->isAllowed( 'autoconfirmed' );
2439 }
2440
2441 /**
2442 * Is the user active? We check to see if they've made at least
2443 * X number of edits in the last Y days.
2444 *
2445 * @return bool true if the user is active, false if not
2446 */
2447 public function isActiveEditor() {
2448 global $wgActiveUserEditCount, $wgActiveUserDays;
2449 $dbr = wfGetDB( DB_SLAVE );
2450
2451 // Stolen without shame from RC
2452 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2453 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2454 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2455
2456 $res = $dbr->select( 'revision', '1',
2457 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2458 __METHOD__,
2459 array('LIMIT' => $wgActiveUserEditCount ) );
2460
2461 $count = $dbr->numRows($res);
2462 $dbr->freeResult($res);
2463
2464 return $count == $wgActiveUserEditCount;
2465 }
2466
2467 /**
2468 * Check to see if the given clear-text password is one of the accepted passwords
2469 * @param string $password User password.
2470 * @return bool True if the given password is correct otherwise False.
2471 */
2472 function checkPassword( $password ) {
2473 global $wgAuth;
2474 $this->load();
2475
2476 // Even though we stop people from creating passwords that
2477 // are shorter than this, doesn't mean people wont be able
2478 // to. Certain authentication plugins do NOT want to save
2479 // domain passwords in a mysql database, so we should
2480 // check this (incase $wgAuth->strict() is false).
2481 if( !$this->isValidPassword( $password ) ) {
2482 return false;
2483 }
2484
2485 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2486 return true;
2487 } elseif( $wgAuth->strict() ) {
2488 /* Auth plugin doesn't allow local authentication */
2489 return false;
2490 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2491 /* Auth plugin doesn't allow local authentication for this user name */
2492 return false;
2493 }
2494 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2495 return true;
2496 } elseif ( function_exists( 'iconv' ) ) {
2497 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2498 # Check for this with iconv
2499 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2500 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2501 return true;
2502 }
2503 }
2504 return false;
2505 }
2506
2507 /**
2508 * Check if the given clear-text password matches the temporary password
2509 * sent by e-mail for password reset operations.
2510 * @return bool
2511 */
2512 function checkTemporaryPassword( $plaintext ) {
2513 return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() );
2514 }
2515
2516 /**
2517 * Initialize (if necessary) and return a session token value
2518 * which can be used in edit forms to show that the user's
2519 * login credentials aren't being hijacked with a foreign form
2520 * submission.
2521 *
2522 * @param mixed $salt - Optional function-specific data for hash.
2523 * Use a string or an array of strings.
2524 * @return string
2525 * @public
2526 */
2527 function editToken( $salt = '' ) {
2528 if ( $this->isAnon() ) {
2529 return EDIT_TOKEN_SUFFIX;
2530 } else {
2531 if( !isset( $_SESSION['wsEditToken'] ) ) {
2532 $token = $this->generateToken();
2533 $_SESSION['wsEditToken'] = $token;
2534 } else {
2535 $token = $_SESSION['wsEditToken'];
2536 }
2537 if( is_array( $salt ) ) {
2538 $salt = implode( '|', $salt );
2539 }
2540 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2541 }
2542 }
2543
2544 /**
2545 * Generate a hex-y looking random token for various uses.
2546 * Could be made more cryptographically sure if someone cares.
2547 * @return string
2548 */
2549 function generateToken( $salt = '' ) {
2550 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2551 return md5( $token . $salt );
2552 }
2553
2554 /**
2555 * Check given value against the token value stored in the session.
2556 * A match should confirm that the form was submitted from the
2557 * user's own login session, not a form submission from a third-party
2558 * site.
2559 *
2560 * @param string $val - the input value to compare
2561 * @param string $salt - Optional function-specific data for hash
2562 * @return bool
2563 * @public
2564 */
2565 function matchEditToken( $val, $salt = '' ) {
2566 $sessionToken = $this->editToken( $salt );
2567 if ( $val != $sessionToken ) {
2568 wfDebug( "User::matchEditToken: broken session data\n" );
2569 }
2570 return $val == $sessionToken;
2571 }
2572
2573 /**
2574 * Check whether the edit token is fine except for the suffix
2575 */
2576 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2577 $sessionToken = $this->editToken( $salt );
2578 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2579 }
2580
2581 /**
2582 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2583 * mail to the user's given address.
2584 *
2585 * Calls saveSettings() internally; as it has side effects, not committing changes
2586 * would be pretty silly.
2587 *
2588 * @return mixed True on success, a WikiError object on failure.
2589 */
2590 function sendConfirmationMail() {
2591 global $wgLang;
2592 $expiration = null; // gets passed-by-ref and defined in next line.
2593 $token = $this->confirmationToken( $expiration );
2594 $url = $this->confirmationTokenUrl( $token );
2595 $invalidateURL = $this->invalidationTokenUrl( $token );
2596 $this->saveSettings();
2597
2598 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2599 wfMsg( 'confirmemail_body',
2600 wfGetIP(),
2601 $this->getName(),
2602 $url,
2603 $wgLang->timeanddate( $expiration, false ),
2604 $invalidateURL ) );
2605 }
2606
2607 /**
2608 * Send an e-mail to this user's account. Does not check for
2609 * confirmed status or validity.
2610 *
2611 * @param string $subject
2612 * @param string $body
2613 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2614 * @return mixed True on success, a WikiError object on failure.
2615 */
2616 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2617 if( is_null( $from ) ) {
2618 global $wgPasswordSender;
2619 $from = $wgPasswordSender;
2620 }
2621
2622 $to = new MailAddress( $this );
2623 $sender = new MailAddress( $from );
2624 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2625 }
2626
2627 /**
2628 * Generate, store, and return a new e-mail confirmation code.
2629 * A hash (unsalted since it's used as a key) is stored.
2630 *
2631 * Call saveSettings() after calling this function to commit
2632 * this change to the database.
2633 *
2634 * @param &$expiration mixed output: accepts the expiration time
2635 * @return string
2636 * @private
2637 */
2638 function confirmationToken( &$expiration ) {
2639 $now = time();
2640 $expires = $now + 7 * 24 * 60 * 60;
2641 $expiration = wfTimestamp( TS_MW, $expires );
2642 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2643 $hash = md5( $token );
2644 $this->load();
2645 $this->mEmailToken = $hash;
2646 $this->mEmailTokenExpires = $expiration;
2647 return $token;
2648 }
2649
2650 /**
2651 * Return a URL the user can use to confirm their email address.
2652 * @param $token: accepts the email confirmation token
2653 * @return string
2654 * @private
2655 */
2656 function confirmationTokenUrl( $token ) {
2657 return $this->getTokenUrl( 'ConfirmEmail', $token );
2658 }
2659 /**
2660 * Return a URL the user can use to invalidate their email address.
2661 * @param $token: accepts the email confirmation token
2662 * @return string
2663 * @private
2664 */
2665 function invalidationTokenUrl( $token ) {
2666 return $this->getTokenUrl( 'Invalidateemail', $token );
2667 }
2668
2669 /**
2670 * Internal function to format the e-mail validation/invalidation URLs.
2671 * This uses $wgArticlePath directly as a quickie hack to use the
2672 * hardcoded English names of the Special: pages, for ASCII safety.
2673 *
2674 * Since these URLs get dropped directly into emails, using the
2675 * short English names avoids insanely long URL-encoded links, which
2676 * also sometimes can get corrupted in some browsers/mailers
2677 * (bug 6957 with Gmail and Internet Explorer).
2678 */
2679 protected function getTokenUrl( $page, $token ) {
2680 global $wgArticlePath;
2681 return wfExpandUrl(
2682 str_replace(
2683 '$1',
2684 "Special:$page/$token",
2685 $wgArticlePath ) );
2686 }
2687
2688 /**
2689 * Mark the e-mail address confirmed.
2690 *
2691 * Call saveSettings() after calling this function to commit the change.
2692 */
2693 function confirmEmail() {
2694 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2695 return true;
2696 }
2697
2698 /**
2699 * Invalidate the user's email confirmation, unauthenticate the email
2700 * if it was already confirmed.
2701 *
2702 * Call saveSettings() after calling this function to commit the change.
2703 */
2704 function invalidateEmail() {
2705 $this->load();
2706 $this->mEmailToken = null;
2707 $this->mEmailTokenExpires = null;
2708 $this->setEmailAuthenticationTimestamp( null );
2709 return true;
2710 }
2711
2712 function setEmailAuthenticationTimestamp( $timestamp ) {
2713 $this->load();
2714 $this->mEmailAuthenticated = $timestamp;
2715 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2716 }
2717
2718 /**
2719 * Is this user allowed to send e-mails within limits of current
2720 * site configuration?
2721 * @return bool
2722 */
2723 function canSendEmail() {
2724 $canSend = $this->isEmailConfirmed();
2725 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2726 return $canSend;
2727 }
2728
2729 /**
2730 * Is this user allowed to receive e-mails within limits of current
2731 * site configuration?
2732 * @return bool
2733 */
2734 function canReceiveEmail() {
2735 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2736 }
2737
2738 /**
2739 * Is this user's e-mail address valid-looking and confirmed within
2740 * limits of the current site configuration?
2741 *
2742 * If $wgEmailAuthentication is on, this may require the user to have
2743 * confirmed their address by returning a code or using a password
2744 * sent to the address from the wiki.
2745 *
2746 * @return bool
2747 */
2748 function isEmailConfirmed() {
2749 global $wgEmailAuthentication;
2750 $this->load();
2751 $confirmed = true;
2752 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2753 if( $this->isAnon() )
2754 return false;
2755 if( !self::isValidEmailAddr( $this->mEmail ) )
2756 return false;
2757 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2758 return false;
2759 return true;
2760 } else {
2761 return $confirmed;
2762 }
2763 }
2764
2765 /**
2766 * Return true if there is an outstanding request for e-mail confirmation.
2767 * @return bool
2768 */
2769 function isEmailConfirmationPending() {
2770 global $wgEmailAuthentication;
2771 return $wgEmailAuthentication &&
2772 !$this->isEmailConfirmed() &&
2773 $this->mEmailToken &&
2774 $this->mEmailTokenExpires > wfTimestamp();
2775 }
2776
2777 /**
2778 * Get the timestamp of account creation, or false for
2779 * non-existent/anonymous user accounts
2780 *
2781 * @return mixed
2782 */
2783 public function getRegistration() {
2784 return $this->mId > 0
2785 ? $this->mRegistration
2786 : false;
2787 }
2788
2789 /**
2790 * @param array $groups list of groups
2791 * @return array list of permission key names for given groups combined
2792 */
2793 static function getGroupPermissions( $groups ) {
2794 global $wgGroupPermissions;
2795 $rights = array();
2796 foreach( $groups as $group ) {
2797 if( isset( $wgGroupPermissions[$group] ) ) {
2798 $rights = array_merge( $rights,
2799 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2800 }
2801 }
2802 return $rights;
2803 }
2804
2805 /**
2806 * @param string $group key name
2807 * @return string localized descriptive name for group, if provided
2808 */
2809 static function getGroupName( $group ) {
2810 global $wgMessageCache;
2811 $wgMessageCache->loadAllMessages();
2812 $key = "group-$group";
2813 $name = wfMsg( $key );
2814 return $name == '' || wfEmptyMsg( $key, $name )
2815 ? $group
2816 : $name;
2817 }
2818
2819 /**
2820 * @param string $group key name
2821 * @return string localized descriptive name for member of a group, if provided
2822 */
2823 static function getGroupMember( $group ) {
2824 global $wgMessageCache;
2825 $wgMessageCache->loadAllMessages();
2826 $key = "group-$group-member";
2827 $name = wfMsg( $key );
2828 return $name == '' || wfEmptyMsg( $key, $name )
2829 ? $group
2830 : $name;
2831 }
2832
2833 /**
2834 * Return the set of defined explicit groups.
2835 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2836 * are not included, as they are defined automatically,
2837 * not in the database.
2838 * @return array
2839 */
2840 static function getAllGroups() {
2841 global $wgGroupPermissions;
2842 return array_diff(
2843 array_keys( $wgGroupPermissions ),
2844 self::getImplicitGroups()
2845 );
2846 }
2847
2848 /**
2849 * Get a list of all available permissions
2850 */
2851 static function getAllRights() {
2852 if ( self::$mAllRights === false ) {
2853 global $wgAvailableRights;
2854 if ( count( $wgAvailableRights ) ) {
2855 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
2856 } else {
2857 self::$mAllRights = self::$mCoreRights;
2858 }
2859 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
2860 }
2861 return self::$mAllRights;
2862 }
2863
2864 /**
2865 * Get a list of implicit groups
2866 *
2867 * @return array
2868 */
2869 public static function getImplicitGroups() {
2870 global $wgImplicitGroups;
2871 $groups = $wgImplicitGroups;
2872 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2873 return $groups;
2874 }
2875
2876 /**
2877 * Get the title of a page describing a particular group
2878 *
2879 * @param $group Name of the group
2880 * @return mixed
2881 */
2882 static function getGroupPage( $group ) {
2883 global $wgMessageCache;
2884 $wgMessageCache->loadAllMessages();
2885 $page = wfMsgForContent( 'grouppage-' . $group );
2886 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2887 $title = Title::newFromText( $page );
2888 if( is_object( $title ) )
2889 return $title;
2890 }
2891 return false;
2892 }
2893
2894 /**
2895 * Create a link to the group in HTML, if available
2896 *
2897 * @param $group Name of the group
2898 * @param $text The text of the link
2899 * @return mixed
2900 */
2901 static function makeGroupLinkHTML( $group, $text = '' ) {
2902 if( $text == '' ) {
2903 $text = self::getGroupName( $group );
2904 }
2905 $title = self::getGroupPage( $group );
2906 if( $title ) {
2907 global $wgUser;
2908 $sk = $wgUser->getSkin();
2909 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2910 } else {
2911 return $text;
2912 }
2913 }
2914
2915 /**
2916 * Create a link to the group in Wikitext, if available
2917 *
2918 * @param $group Name of the group
2919 * @param $text The text of the link (by default, the name of the group)
2920 * @return mixed
2921 */
2922 static function makeGroupLinkWiki( $group, $text = '' ) {
2923 if( $text == '' ) {
2924 $text = self::getGroupName( $group );
2925 }
2926 $title = self::getGroupPage( $group );
2927 if( $title ) {
2928 $page = $title->getPrefixedText();
2929 return "[[$page|$text]]";
2930 } else {
2931 return $text;
2932 }
2933 }
2934
2935 /**
2936 * Increment the user's edit-count field.
2937 * Will have no effect for anonymous users.
2938 */
2939 function incEditCount() {
2940 if( !$this->isAnon() ) {
2941 $dbw = wfGetDB( DB_MASTER );
2942 $dbw->update( 'user',
2943 array( 'user_editcount=user_editcount+1' ),
2944 array( 'user_id' => $this->getId() ),
2945 __METHOD__ );
2946
2947 // Lazy initialization check...
2948 if( $dbw->affectedRows() == 0 ) {
2949 // Pull from a slave to be less cruel to servers
2950 // Accuracy isn't the point anyway here
2951 $dbr = wfGetDB( DB_SLAVE );
2952 $count = $dbr->selectField( 'revision',
2953 'COUNT(rev_user)',
2954 array( 'rev_user' => $this->getId() ),
2955 __METHOD__ );
2956
2957 // Now here's a goddamn hack...
2958 if( $dbr !== $dbw ) {
2959 // If we actually have a slave server, the count is
2960 // at least one behind because the current transaction
2961 // has not been committed and replicated.
2962 $count++;
2963 } else {
2964 // But if DB_SLAVE is selecting the master, then the
2965 // count we just read includes the revision that was
2966 // just added in the working transaction.
2967 }
2968
2969 $dbw->update( 'user',
2970 array( 'user_editcount' => $count ),
2971 array( 'user_id' => $this->getId() ),
2972 __METHOD__ );
2973 }
2974 }
2975 // edit count in user cache too
2976 $this->invalidateCache();
2977 }
2978
2979 static function getRightDescription( $right ) {
2980 global $wgMessageCache;
2981 $wgMessageCache->loadAllMessages();
2982 $key = "right-$right";
2983 $name = wfMsg( $key );
2984 return $name == '' || wfEmptyMsg( $key, $name )
2985 ? $right
2986 : $name;
2987 }
2988
2989 /**
2990 * Make an old-style password hash
2991 *
2992 * @param string $password Plain-text password
2993 * @param string $userId User ID
2994 */
2995 static function oldCrypt( $password, $userId ) {
2996 global $wgPasswordSalt;
2997 if ( $wgPasswordSalt ) {
2998 return md5( $userId . '-' . md5( $password ) );
2999 } else {
3000 return md5( $password );
3001 }
3002 }
3003
3004 /**
3005 * Make a new-style password hash
3006 *
3007 * @param string $password Plain-text password
3008 * @param string $salt Salt, may be random or the user ID. False to generate a salt.
3009 */
3010 static function crypt( $password, $salt = false ) {
3011 global $wgPasswordSalt;
3012
3013 if($wgPasswordSalt) {
3014 if ( $salt === false ) {
3015 $salt = substr( wfGenerateToken(), 0, 8 );
3016 }
3017 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3018 } else {
3019 return ':A:' . md5( $password);
3020 }
3021 }
3022
3023 /**
3024 * Compare a password hash with a plain-text password. Requires the user
3025 * ID if there's a chance that the hash is an old-style hash.
3026 *
3027 * @param string $hash Password hash
3028 * @param string $password Plain-text password to compare
3029 * @param string $userId User ID for old-style password salt
3030 */
3031 static function comparePasswords( $hash, $password, $userId = false ) {
3032 $m = false;
3033 $type = substr( $hash, 0, 3 );
3034 if ( $type == ':A:' ) {
3035 # Unsalted
3036 return md5( $password ) === substr( $hash, 3 );
3037 } elseif ( $type == ':B:' ) {
3038 # Salted
3039 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3040 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3041 } else {
3042 # Old-style
3043 return self::oldCrypt( $password, $userId ) === $hash;
3044 }
3045 }
3046 }