Some more tweaks to Special:Recentchanges:
[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 */
966 public static function getDefaultOption( $opt ) {
967 $defOpts = self::getDefaultOptions();
968 if( isset( $defOpts[$opt] ) ) {
969 return $defOpts[$opt];
970 } else {
971 return '';
972 }
973 }
974
975 /**
976 * Get a list of user toggle names
977 * @return array
978 */
979 static function getToggles() {
980 global $wgContLang;
981 $extraToggles = array();
982 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
983 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
984 }
985
986
987 /**
988 * Get blocking information
989 * @private
990 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
991 * non-critical checks are done against slaves. Check when actually saving should be done against
992 * master.
993 */
994 function getBlockedStatus( $bFromSlave = true ) {
995 global $wgEnableSorbs, $wgProxyWhitelist;
996
997 if ( -1 != $this->mBlockedby ) {
998 wfDebug( "User::getBlockedStatus: already loaded.\n" );
999 return;
1000 }
1001
1002 wfProfileIn( __METHOD__ );
1003 wfDebug( __METHOD__.": checking...\n" );
1004
1005 // Initialize data...
1006 // Otherwise something ends up stomping on $this->mBlockedby when
1007 // things get lazy-loaded later, causing false positive block hits
1008 // due to -1 !== 0. Probably session-related... Nothing should be
1009 // overwriting mBlockedby, surely?
1010 $this->load();
1011
1012 $this->mBlockedby = 0;
1013 $this->mHideName = 0;
1014 $ip = wfGetIP();
1015
1016 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1017 # Exempt from all types of IP-block
1018 $ip = '';
1019 }
1020
1021 # User/IP blocking
1022 $this->mBlock = new Block();
1023 $this->mBlock->fromMaster( !$bFromSlave );
1024 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1025 wfDebug( __METHOD__.": Found block.\n" );
1026 $this->mBlockedby = $this->mBlock->mBy;
1027 $this->mBlockreason = $this->mBlock->mReason;
1028 $this->mHideName = $this->mBlock->mHideName;
1029 if ( $this->isLoggedIn() ) {
1030 $this->spreadBlock();
1031 }
1032 } else {
1033 $this->mBlock = null;
1034 wfDebug( __METHOD__.": No block.\n" );
1035 }
1036
1037 # Proxy blocking
1038 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1039 # Local list
1040 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1041 $this->mBlockedby = wfMsg( 'proxyblocker' );
1042 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1043 }
1044
1045 # DNSBL
1046 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1047 if ( $this->inSorbsBlacklist( $ip ) ) {
1048 $this->mBlockedby = wfMsg( 'sorbs' );
1049 $this->mBlockreason = wfMsg( 'sorbsreason' );
1050 }
1051 }
1052 }
1053
1054 # Extensions
1055 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1056
1057 wfProfileOut( __METHOD__ );
1058 }
1059
1060 function inSorbsBlacklist( $ip ) {
1061 global $wgEnableSorbs, $wgSorbsUrl;
1062
1063 return $wgEnableSorbs &&
1064 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1065 }
1066
1067 function inDnsBlacklist( $ip, $base ) {
1068 wfProfileIn( __METHOD__ );
1069
1070 $found = false;
1071 $host = '';
1072 // FIXME: IPv6 ???
1073 $m = array();
1074 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1075 # Make hostname
1076 for ( $i=4; $i>=1; $i-- ) {
1077 $host .= $m[$i] . '.';
1078 }
1079 $host .= $base;
1080
1081 # Send query
1082 $ipList = gethostbynamel( $host );
1083
1084 if ( $ipList ) {
1085 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1086 $found = true;
1087 } else {
1088 wfDebug( "Requested $host, not found in $base.\n" );
1089 }
1090 }
1091
1092 wfProfileOut( __METHOD__ );
1093 return $found;
1094 }
1095
1096 /**
1097 * Is this user subject to rate limiting?
1098 *
1099 * @return bool
1100 */
1101 public function isPingLimitable() {
1102 global $wgRateLimitsExcludedGroups;
1103 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1104 // Deprecated, but kept for backwards-compatibility config
1105 return false;
1106 }
1107 return !$this->isAllowed('noratelimit');
1108 }
1109
1110 /**
1111 * Primitive rate limits: enforce maximum actions per time period
1112 * to put a brake on flooding.
1113 *
1114 * Note: when using a shared cache like memcached, IP-address
1115 * last-hit counters will be shared across wikis.
1116 *
1117 * @return bool true if a rate limiter was tripped
1118 * @public
1119 */
1120 function pingLimiter( $action='edit' ) {
1121
1122 # Call the 'PingLimiter' hook
1123 $result = false;
1124 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1125 return $result;
1126 }
1127
1128 global $wgRateLimits;
1129 if( !isset( $wgRateLimits[$action] ) ) {
1130 return false;
1131 }
1132
1133 # Some groups shouldn't trigger the ping limiter, ever
1134 if( !$this->isPingLimitable() )
1135 return false;
1136
1137 global $wgMemc, $wgRateLimitLog;
1138 wfProfileIn( __METHOD__ );
1139
1140 $limits = $wgRateLimits[$action];
1141 $keys = array();
1142 $id = $this->getId();
1143 $ip = wfGetIP();
1144 $userLimit = false;
1145
1146 if( isset( $limits['anon'] ) && $id == 0 ) {
1147 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1148 }
1149
1150 if( isset( $limits['user'] ) && $id != 0 ) {
1151 $userLimit = $limits['user'];
1152 }
1153 if( $this->isNewbie() ) {
1154 if( isset( $limits['newbie'] ) && $id != 0 ) {
1155 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1156 }
1157 if( isset( $limits['ip'] ) ) {
1158 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1159 }
1160 $matches = array();
1161 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1162 $subnet = $matches[1];
1163 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1164 }
1165 }
1166 // Check for group-specific permissions
1167 // If more than one group applies, use the group with the highest limit
1168 foreach ( $this->getGroups() as $group ) {
1169 if ( isset( $limits[$group] ) ) {
1170 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1171 $userLimit = $limits[$group];
1172 }
1173 }
1174 }
1175 // Set the user limit key
1176 if ( $userLimit !== false ) {
1177 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1178 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1179 }
1180
1181 $triggered = false;
1182 foreach( $keys as $key => $limit ) {
1183 list( $max, $period ) = $limit;
1184 $summary = "(limit $max in {$period}s)";
1185 $count = $wgMemc->get( $key );
1186 if( $count ) {
1187 if( $count > $max ) {
1188 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1189 if( $wgRateLimitLog ) {
1190 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1191 }
1192 $triggered = true;
1193 } else {
1194 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1195 }
1196 } else {
1197 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1198 $wgMemc->add( $key, 1, intval( $period ) );
1199 }
1200 $wgMemc->incr( $key );
1201 }
1202
1203 wfProfileOut( __METHOD__ );
1204 return $triggered;
1205 }
1206
1207 /**
1208 * Check if user is blocked
1209 * @return bool True if blocked, false otherwise
1210 */
1211 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1212 wfDebug( "User::isBlocked: enter\n" );
1213 $this->getBlockedStatus( $bFromSlave );
1214 return $this->mBlockedby !== 0;
1215 }
1216
1217 /**
1218 * Check if user is blocked from editing a particular article
1219 */
1220 function isBlockedFrom( $title, $bFromSlave = false ) {
1221 global $wgBlockAllowsUTEdit;
1222 wfProfileIn( __METHOD__ );
1223 wfDebug( __METHOD__.": enter\n" );
1224
1225 wfDebug( __METHOD__.": asking isBlocked()\n" );
1226 $blocked = $this->isBlocked( $bFromSlave );
1227 # If a user's name is suppressed, they cannot make edits anywhere
1228 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1229 $title->getNamespace() == NS_USER_TALK ) {
1230 $blocked = false;
1231 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1232 }
1233 wfProfileOut( __METHOD__ );
1234 return $blocked;
1235 }
1236
1237 /**
1238 * Get name of blocker
1239 * @return string name of blocker
1240 */
1241 function blockedBy() {
1242 $this->getBlockedStatus();
1243 return $this->mBlockedby;
1244 }
1245
1246 /**
1247 * Get blocking reason
1248 * @return string Blocking reason
1249 */
1250 function blockedFor() {
1251 $this->getBlockedStatus();
1252 return $this->mBlockreason;
1253 }
1254
1255 /**
1256 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1257 */
1258 function getId() {
1259 if( $this->mId === null and $this->mName !== null
1260 and User::isIP( $this->mName ) ) {
1261 // Special case, we know the user is anonymous
1262 return 0;
1263 } elseif( $this->mId === null ) {
1264 // Don't load if this was initialized from an ID
1265 $this->load();
1266 }
1267 return $this->mId;
1268 }
1269
1270 /**
1271 * Set the user and reload all fields according to that ID
1272 */
1273 function setId( $v ) {
1274 $this->mId = $v;
1275 $this->clearInstanceCache( 'id' );
1276 }
1277
1278 /**
1279 * Get the user name, or the IP for anons
1280 */
1281 function getName() {
1282 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1283 # Special case optimisation
1284 return $this->mName;
1285 } else {
1286 $this->load();
1287 if ( $this->mName === false ) {
1288 # Clean up IPs
1289 $this->mName = IP::sanitizeIP( wfGetIP() );
1290 }
1291 return $this->mName;
1292 }
1293 }
1294
1295 /**
1296 * Set the user name.
1297 *
1298 * This does not reload fields from the database according to the given
1299 * name. Rather, it is used to create a temporary "nonexistent user" for
1300 * later addition to the database. It can also be used to set the IP
1301 * address for an anonymous user to something other than the current
1302 * remote IP.
1303 *
1304 * User::newFromName() has rougly the same function, when the named user
1305 * does not exist.
1306 */
1307 function setName( $str ) {
1308 $this->load();
1309 $this->mName = $str;
1310 }
1311
1312 /**
1313 * Return the title dbkey form of the name, for eg user pages.
1314 * @return string
1315 * @public
1316 */
1317 function getTitleKey() {
1318 return str_replace( ' ', '_', $this->getName() );
1319 }
1320
1321 function getNewtalk() {
1322 $this->load();
1323
1324 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1325 if( $this->mNewtalk === -1 ) {
1326 $this->mNewtalk = false; # reset talk page status
1327
1328 # Check memcached separately for anons, who have no
1329 # entire User object stored in there.
1330 if( !$this->mId ) {
1331 global $wgMemc;
1332 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1333 $newtalk = $wgMemc->get( $key );
1334 if( strval( $newtalk ) !== '' ) {
1335 $this->mNewtalk = (bool)$newtalk;
1336 } else {
1337 // Since we are caching this, make sure it is up to date by getting it
1338 // from the master
1339 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1340 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1341 }
1342 } else {
1343 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1344 }
1345 }
1346
1347 return (bool)$this->mNewtalk;
1348 }
1349
1350 /**
1351 * Return the talk page(s) this user has new messages on.
1352 */
1353 function getNewMessageLinks() {
1354 $talks = array();
1355 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1356 return $talks;
1357
1358 if (!$this->getNewtalk())
1359 return array();
1360 $up = $this->getUserPage();
1361 $utp = $up->getTalkPage();
1362 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1363 }
1364
1365
1366 /**
1367 * Perform a user_newtalk check, uncached.
1368 * Use getNewtalk for a cached check.
1369 *
1370 * @param string $field
1371 * @param mixed $id
1372 * @param bool $fromMaster True to fetch from the master, false for a slave
1373 * @return bool
1374 * @private
1375 */
1376 function checkNewtalk( $field, $id, $fromMaster = false ) {
1377 if ( $fromMaster ) {
1378 $db = wfGetDB( DB_MASTER );
1379 } else {
1380 $db = wfGetDB( DB_SLAVE );
1381 }
1382 $ok = $db->selectField( 'user_newtalk', $field,
1383 array( $field => $id ), __METHOD__ );
1384 return $ok !== false;
1385 }
1386
1387 /**
1388 * Add or update the
1389 * @param string $field
1390 * @param mixed $id
1391 * @private
1392 */
1393 function updateNewtalk( $field, $id ) {
1394 $dbw = wfGetDB( DB_MASTER );
1395 $dbw->insert( 'user_newtalk',
1396 array( $field => $id ),
1397 __METHOD__,
1398 'IGNORE' );
1399 if ( $dbw->affectedRows() ) {
1400 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1401 return true;
1402 } else {
1403 wfDebug( __METHOD__." already set ($field, $id)\n" );
1404 return false;
1405 }
1406 }
1407
1408 /**
1409 * Clear the new messages flag for the given user
1410 * @param string $field
1411 * @param mixed $id
1412 * @private
1413 */
1414 function deleteNewtalk( $field, $id ) {
1415 $dbw = wfGetDB( DB_MASTER );
1416 $dbw->delete( 'user_newtalk',
1417 array( $field => $id ),
1418 __METHOD__ );
1419 if ( $dbw->affectedRows() ) {
1420 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1421 return true;
1422 } else {
1423 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1424 return false;
1425 }
1426 }
1427
1428 /**
1429 * Update the 'You have new messages!' status.
1430 * @param bool $val
1431 */
1432 function setNewtalk( $val ) {
1433 if( wfReadOnly() ) {
1434 return;
1435 }
1436
1437 $this->load();
1438 $this->mNewtalk = $val;
1439
1440 if( $this->isAnon() ) {
1441 $field = 'user_ip';
1442 $id = $this->getName();
1443 } else {
1444 $field = 'user_id';
1445 $id = $this->getId();
1446 }
1447 global $wgMemc;
1448
1449 if( $val ) {
1450 $changed = $this->updateNewtalk( $field, $id );
1451 } else {
1452 $changed = $this->deleteNewtalk( $field, $id );
1453 }
1454
1455 if( $this->isAnon() ) {
1456 // Anons have a separate memcached space, since
1457 // user records aren't kept for them.
1458 $key = wfMemcKey( 'newtalk', 'ip', $id );
1459 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1460 }
1461 if ( $changed ) {
1462 $this->invalidateCache();
1463 }
1464 }
1465
1466 /**
1467 * Generate a current or new-future timestamp to be stored in the
1468 * user_touched field when we update things.
1469 */
1470 private static function newTouchedTimestamp() {
1471 global $wgClockSkewFudge;
1472 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1473 }
1474
1475 /**
1476 * Clear user data from memcached.
1477 * Use after applying fun updates to the database; caller's
1478 * responsibility to update user_touched if appropriate.
1479 *
1480 * Called implicitly from invalidateCache() and saveSettings().
1481 */
1482 private function clearSharedCache() {
1483 if( $this->mId ) {
1484 global $wgMemc;
1485 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1486 }
1487 }
1488
1489 /**
1490 * Immediately touch the user data cache for this account.
1491 * Updates user_touched field, and removes account data from memcached
1492 * for reload on the next hit.
1493 */
1494 function invalidateCache() {
1495 $this->load();
1496 if( $this->mId ) {
1497 $this->mTouched = self::newTouchedTimestamp();
1498
1499 $dbw = wfGetDB( DB_MASTER );
1500 $dbw->update( 'user',
1501 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1502 array( 'user_id' => $this->mId ),
1503 __METHOD__ );
1504
1505 $this->clearSharedCache();
1506 }
1507 }
1508
1509 function validateCache( $timestamp ) {
1510 $this->load();
1511 return ($timestamp >= $this->mTouched);
1512 }
1513
1514 /**
1515 * Set the password and reset the random token
1516 * Calls through to authentication plugin if necessary;
1517 * will have no effect if the auth plugin refuses to
1518 * pass the change through or if the legal password
1519 * checks fail.
1520 *
1521 * As a special case, setting the password to null
1522 * wipes it, so the account cannot be logged in until
1523 * a new password is set, for instance via e-mail.
1524 *
1525 * @param string $str
1526 * @throws PasswordError on failure
1527 */
1528 function setPassword( $str ) {
1529 global $wgAuth;
1530
1531 if( $str !== null ) {
1532 if( !$wgAuth->allowPasswordChange() ) {
1533 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1534 }
1535
1536 if( !$this->isValidPassword( $str ) ) {
1537 global $wgMinimalPasswordLength;
1538 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1539 $wgMinimalPasswordLength ) );
1540 }
1541 }
1542
1543 if( !$wgAuth->setPassword( $this, $str ) ) {
1544 throw new PasswordError( wfMsg( 'externaldberror' ) );
1545 }
1546
1547 $this->setInternalPassword( $str );
1548
1549 return true;
1550 }
1551
1552 /**
1553 * Set the password and reset the random token no matter
1554 * what.
1555 *
1556 * @param string $str
1557 */
1558 function setInternalPassword( $str ) {
1559 $this->load();
1560 $this->setToken();
1561
1562 if( $str === null ) {
1563 // Save an invalid hash...
1564 $this->mPassword = '';
1565 } else {
1566 $this->mPassword = self::crypt( $str );
1567 }
1568 $this->mNewpassword = '';
1569 $this->mNewpassTime = null;
1570 }
1571
1572 function getToken() {
1573 $this->load();
1574 return $this->mToken;
1575 }
1576
1577 /**
1578 * Set the random token (used for persistent authentication)
1579 * Called from loadDefaults() among other places.
1580 * @private
1581 */
1582 function setToken( $token = false ) {
1583 global $wgSecretKey, $wgProxyKey;
1584 $this->load();
1585 if ( !$token ) {
1586 if ( $wgSecretKey ) {
1587 $key = $wgSecretKey;
1588 } elseif ( $wgProxyKey ) {
1589 $key = $wgProxyKey;
1590 } else {
1591 $key = microtime();
1592 }
1593 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1594 } else {
1595 $this->mToken = $token;
1596 }
1597 }
1598
1599 function setCookiePassword( $str ) {
1600 $this->load();
1601 $this->mCookiePassword = md5( $str );
1602 }
1603
1604 /**
1605 * Set the password for a password reminder or new account email
1606 * Sets the user_newpass_time field if $throttle is true
1607 */
1608 function setNewpassword( $str, $throttle = true ) {
1609 $this->load();
1610 $this->mNewpassword = self::crypt( $str );
1611 if ( $throttle ) {
1612 $this->mNewpassTime = wfTimestampNow();
1613 }
1614 }
1615
1616 /**
1617 * Returns true if a password reminder email has already been sent within
1618 * the last $wgPasswordReminderResendTime hours
1619 */
1620 function isPasswordReminderThrottled() {
1621 global $wgPasswordReminderResendTime;
1622 $this->load();
1623 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1624 return false;
1625 }
1626 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1627 return time() < $expiry;
1628 }
1629
1630 function getEmail() {
1631 $this->load();
1632 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1633 return $this->mEmail;
1634 }
1635
1636 function getEmailAuthenticationTimestamp() {
1637 $this->load();
1638 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1639 return $this->mEmailAuthenticated;
1640 }
1641
1642 function setEmail( $str ) {
1643 $this->load();
1644 $this->mEmail = $str;
1645 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1646 }
1647
1648 function getRealName() {
1649 $this->load();
1650 return $this->mRealName;
1651 }
1652
1653 function setRealName( $str ) {
1654 $this->load();
1655 $this->mRealName = $str;
1656 }
1657
1658 /**
1659 * @param string $oname The option to check
1660 * @param string $defaultOverride A default value returned if the option does not exist
1661 * @return string
1662 */
1663 function getOption( $oname, $defaultOverride = '' ) {
1664 $this->load();
1665
1666 if ( is_null( $this->mOptions ) ) {
1667 if($defaultOverride != '') {
1668 return $defaultOverride;
1669 }
1670 $this->mOptions = User::getDefaultOptions();
1671 }
1672
1673 if ( array_key_exists( $oname, $this->mOptions ) ) {
1674 return trim( $this->mOptions[$oname] );
1675 } else {
1676 return $defaultOverride;
1677 }
1678 }
1679
1680 /**
1681 * Get the user's date preference, including some important migration for
1682 * old user rows.
1683 */
1684 function getDatePreference() {
1685 if ( is_null( $this->mDatePreference ) ) {
1686 global $wgLang;
1687 $value = $this->getOption( 'date' );
1688 $map = $wgLang->getDatePreferenceMigrationMap();
1689 if ( isset( $map[$value] ) ) {
1690 $value = $map[$value];
1691 }
1692 $this->mDatePreference = $value;
1693 }
1694 return $this->mDatePreference;
1695 }
1696
1697 /**
1698 * @param string $oname The option to check
1699 * @return bool False if the option is not selected, true if it is
1700 */
1701 function getBoolOption( $oname ) {
1702 return (bool)$this->getOption( $oname );
1703 }
1704
1705 /**
1706 * Get an option as an integer value from the source string.
1707 * @param string $oname The option to check
1708 * @param int $default Optional value to return if option is unset/blank.
1709 * @return int
1710 */
1711 function getIntOption( $oname, $default=0 ) {
1712 $val = $this->getOption( $oname );
1713 if( $val == '' ) {
1714 $val = $default;
1715 }
1716 return intval( $val );
1717 }
1718
1719 function setOption( $oname, $val ) {
1720 $this->load();
1721 if ( is_null( $this->mOptions ) ) {
1722 $this->mOptions = User::getDefaultOptions();
1723 }
1724 if ( $oname == 'skin' ) {
1725 # Clear cached skin, so the new one displays immediately in Special:Preferences
1726 unset( $this->mSkin );
1727 }
1728 // Filter out any newlines that may have passed through input validation.
1729 // Newlines are used to separate items in the options blob.
1730 if( $val ) {
1731 $val = str_replace( "\r\n", "\n", $val );
1732 $val = str_replace( "\r", "\n", $val );
1733 $val = str_replace( "\n", " ", $val );
1734 }
1735 // Explicitly NULL values should refer to defaults
1736 global $wgDefaultUserOptions;
1737 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1738 $val = $wgDefaultUserOptions[$oname];
1739 }
1740 $this->mOptions[$oname] = $val;
1741 }
1742
1743 function getRights() {
1744 if ( is_null( $this->mRights ) ) {
1745 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1746 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1747 // Force reindexation of rights when a hook has unset one of them
1748 $this->mRights = array_values( $this->mRights );
1749 }
1750 return $this->mRights;
1751 }
1752
1753 /**
1754 * Get the list of explicit group memberships this user has.
1755 * The implicit * and user groups are not included.
1756 * @return array of strings
1757 */
1758 function getGroups() {
1759 $this->load();
1760 return $this->mGroups;
1761 }
1762
1763 /**
1764 * Get the list of implicit group memberships this user has.
1765 * This includes all explicit groups, plus 'user' if logged in,
1766 * '*' for all accounts and autopromoted groups
1767 * @param boolean $recache Don't use the cache
1768 * @return array of strings
1769 */
1770 function getEffectiveGroups( $recache = false ) {
1771 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1772 $this->mEffectiveGroups = $this->getGroups();
1773 $this->mEffectiveGroups[] = '*';
1774 if( $this->getId() ) {
1775 $this->mEffectiveGroups[] = 'user';
1776
1777 $this->mEffectiveGroups = array_unique( array_merge(
1778 $this->mEffectiveGroups,
1779 Autopromote::getAutopromoteGroups( $this )
1780 ) );
1781
1782 # Hook for additional groups
1783 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1784 }
1785 }
1786 return $this->mEffectiveGroups;
1787 }
1788
1789 /* Return the edit count for the user. This is where User::edits should have been */
1790 function getEditCount() {
1791 if ($this->mId) {
1792 if ( !isset( $this->mEditCount ) ) {
1793 /* Populate the count, if it has not been populated yet */
1794 $this->mEditCount = User::edits($this->mId);
1795 }
1796 return $this->mEditCount;
1797 } else {
1798 /* nil */
1799 return null;
1800 }
1801 }
1802
1803 /**
1804 * Add the user to the given group.
1805 * This takes immediate effect.
1806 * @param string $group
1807 */
1808 function addGroup( $group ) {
1809 $dbw = wfGetDB( DB_MASTER );
1810 if( $this->getId() ) {
1811 $dbw->insert( 'user_groups',
1812 array(
1813 'ug_user' => $this->getID(),
1814 'ug_group' => $group,
1815 ),
1816 'User::addGroup',
1817 array( 'IGNORE' ) );
1818 }
1819
1820 $this->loadGroups();
1821 $this->mGroups[] = $group;
1822 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1823
1824 $this->invalidateCache();
1825 }
1826
1827 /**
1828 * Remove the user from the given group.
1829 * This takes immediate effect.
1830 * @param string $group
1831 */
1832 function removeGroup( $group ) {
1833 $this->load();
1834 $dbw = wfGetDB( DB_MASTER );
1835 $dbw->delete( 'user_groups',
1836 array(
1837 'ug_user' => $this->getID(),
1838 'ug_group' => $group,
1839 ),
1840 'User::removeGroup' );
1841
1842 $this->loadGroups();
1843 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1844 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1845
1846 $this->invalidateCache();
1847 }
1848
1849
1850 /**
1851 * A more legible check for non-anonymousness.
1852 * Returns true if the user is not an anonymous visitor.
1853 *
1854 * @return bool
1855 */
1856 function isLoggedIn() {
1857 return $this->getID() != 0;
1858 }
1859
1860 /**
1861 * A more legible check for anonymousness.
1862 * Returns true if the user is an anonymous visitor.
1863 *
1864 * @return bool
1865 */
1866 function isAnon() {
1867 return !$this->isLoggedIn();
1868 }
1869
1870 /**
1871 * Whether the user is a bot
1872 * @deprecated
1873 */
1874 function isBot() {
1875 wfDeprecated( __METHOD__ );
1876 return $this->isAllowed( 'bot' );
1877 }
1878
1879 /**
1880 * Check if user is allowed to access a feature / make an action
1881 * @param string $action Action to be checked
1882 * @return boolean True: action is allowed, False: action should not be allowed
1883 */
1884 function isAllowed($action='') {
1885 if ( $action === '' )
1886 // In the spirit of DWIM
1887 return true;
1888
1889 return in_array( $action, $this->getRights() );
1890 }
1891
1892 /**
1893 * Check whether to enable recent changes patrol features for this user
1894 * @return bool
1895 */
1896 public function useRCPatrol() {
1897 global $wgUseRCPatrol;
1898 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1899 }
1900
1901 /**
1902 * Check whether to enable recent changes patrol features for this user
1903 * @return bool
1904 */
1905 public function useNPPatrol() {
1906 global $wgUseRCPatrol, $wgUseNPPatrol;
1907 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1908 }
1909
1910 /**
1911 * Load a skin if it doesn't exist or return it
1912 * @todo FIXME : need to check the old failback system [AV]
1913 */
1914 function &getSkin() {
1915 global $wgRequest;
1916 if ( ! isset( $this->mSkin ) ) {
1917 wfProfileIn( __METHOD__ );
1918
1919 # get the user skin
1920 $userSkin = $this->getOption( 'skin' );
1921 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1922
1923 $this->mSkin =& Skin::newFromKey( $userSkin );
1924 wfProfileOut( __METHOD__ );
1925 }
1926 return $this->mSkin;
1927 }
1928
1929 /**#@+
1930 * @param string $title Article title to look at
1931 */
1932
1933 /**
1934 * Check watched status of an article
1935 * @return bool True if article is watched
1936 */
1937 function isWatched( $title ) {
1938 $wl = WatchedItem::fromUserTitle( $this, $title );
1939 return $wl->isWatched();
1940 }
1941
1942 /**
1943 * Watch an article
1944 */
1945 function addWatch( $title ) {
1946 $wl = WatchedItem::fromUserTitle( $this, $title );
1947 $wl->addWatch();
1948 $this->invalidateCache();
1949 }
1950
1951 /**
1952 * Stop watching an article
1953 */
1954 function removeWatch( $title ) {
1955 $wl = WatchedItem::fromUserTitle( $this, $title );
1956 $wl->removeWatch();
1957 $this->invalidateCache();
1958 }
1959
1960 /**
1961 * Clear the user's notification timestamp for the given title.
1962 * If e-notif e-mails are on, they will receive notification mails on
1963 * the next change of the page if it's watched etc.
1964 */
1965 function clearNotification( &$title ) {
1966 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1967
1968 # Do nothing if the database is locked to writes
1969 if( wfReadOnly() ) {
1970 return;
1971 }
1972
1973 if ($title->getNamespace() == NS_USER_TALK &&
1974 $title->getText() == $this->getName() ) {
1975 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1976 return;
1977 $this->setNewtalk( false );
1978 }
1979
1980 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1981 return;
1982 }
1983
1984 if( $this->isAnon() ) {
1985 // Nothing else to do...
1986 return;
1987 }
1988
1989 // Only update the timestamp if the page is being watched.
1990 // The query to find out if it is watched is cached both in memcached and per-invocation,
1991 // and when it does have to be executed, it can be on a slave
1992 // If this is the user's newtalk page, we always update the timestamp
1993 if ($title->getNamespace() == NS_USER_TALK &&
1994 $title->getText() == $wgUser->getName())
1995 {
1996 $watched = true;
1997 } elseif ( $this->getId() == $wgUser->getId() ) {
1998 $watched = $title->userIsWatching();
1999 } else {
2000 $watched = true;
2001 }
2002
2003 // If the page is watched by the user (or may be watched), update the timestamp on any
2004 // any matching rows
2005 if ( $watched ) {
2006 $dbw = wfGetDB( DB_MASTER );
2007 $dbw->update( 'watchlist',
2008 array( /* SET */
2009 'wl_notificationtimestamp' => NULL
2010 ), array( /* WHERE */
2011 'wl_title' => $title->getDBkey(),
2012 'wl_namespace' => $title->getNamespace(),
2013 'wl_user' => $this->getID()
2014 ), 'User::clearLastVisited'
2015 );
2016 }
2017 }
2018
2019 /**#@-*/
2020
2021 /**
2022 * Resets all of the given user's page-change notification timestamps.
2023 * If e-notif e-mails are on, they will receive notification mails on
2024 * the next change of any watched page.
2025 *
2026 * @param int $currentUser user ID number
2027 * @public
2028 */
2029 function clearAllNotifications( $currentUser ) {
2030 global $wgUseEnotif, $wgShowUpdatedMarker;
2031 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2032 $this->setNewtalk( false );
2033 return;
2034 }
2035 if( $currentUser != 0 ) {
2036 $dbw = wfGetDB( DB_MASTER );
2037 $dbw->update( 'watchlist',
2038 array( /* SET */
2039 'wl_notificationtimestamp' => NULL
2040 ), array( /* WHERE */
2041 'wl_user' => $currentUser
2042 ), __METHOD__
2043 );
2044 # We also need to clear here the "you have new message" notification for the own user_talk page
2045 # This is cleared one page view later in Article::viewUpdates();
2046 }
2047 }
2048
2049 /**
2050 * @private
2051 * @return string Encoding options
2052 */
2053 function encodeOptions() {
2054 $this->load();
2055 if ( is_null( $this->mOptions ) ) {
2056 $this->mOptions = User::getDefaultOptions();
2057 }
2058 $a = array();
2059 foreach ( $this->mOptions as $oname => $oval ) {
2060 array_push( $a, $oname.'='.$oval );
2061 }
2062 $s = implode( "\n", $a );
2063 return $s;
2064 }
2065
2066 /**
2067 * @private
2068 */
2069 function decodeOptions( $str ) {
2070 $this->mOptions = array();
2071 $a = explode( "\n", $str );
2072 foreach ( $a as $s ) {
2073 $m = array();
2074 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2075 $this->mOptions[$m[1]] = $m[2];
2076 }
2077 }
2078 }
2079
2080 protected function setCookie( $name, $value, $exp=0 ) {
2081 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2082 if( $exp == 0 ) {
2083 $exp = time() + $wgCookieExpiration;
2084 }
2085 $httpOnlySafe = wfHttpOnlySafe();
2086 wfDebugLog( 'cookie',
2087 'setcookie: "' . implode( '", "',
2088 array(
2089 $wgCookiePrefix . $name,
2090 $value,
2091 $exp,
2092 '/',
2093 $wgCookieDomain,
2094 $wgCookieSecure,
2095 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2096 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2097 setcookie( $wgCookiePrefix . $name,
2098 $value,
2099 $exp,
2100 '/',
2101 $wgCookieDomain,
2102 $wgCookieSecure,
2103 $wgCookieHttpOnly );
2104 } else {
2105 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2106 // stab stab!
2107 setcookie( $wgCookiePrefix . $name,
2108 $value,
2109 $exp,
2110 '/',
2111 $wgCookieDomain,
2112 $wgCookieSecure );
2113 }
2114 }
2115
2116 protected function clearCookie( $name ) {
2117 $this->setCookie( $name, '', time() - 86400 );
2118 }
2119
2120 function setCookies() {
2121 $this->load();
2122 if ( 0 == $this->mId ) return;
2123 $session = array(
2124 'wsUserID' => $this->mId,
2125 'wsToken' => $this->mToken,
2126 'wsUserName' => $this->getName()
2127 );
2128 $cookies = array(
2129 'UserID' => $this->mId,
2130 'UserName' => $this->getName(),
2131 );
2132 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2133 $cookies['Token'] = $this->mToken;
2134 } else {
2135 $cookies['Token'] = false;
2136 }
2137
2138 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2139 $_SESSION = $session + $_SESSION;
2140 foreach ( $cookies as $name => $value ) {
2141 if ( $value === false ) {
2142 $this->clearCookie( $name );
2143 } else {
2144 $this->setCookie( $name, $value );
2145 }
2146 }
2147 }
2148
2149 /**
2150 * Logout user.
2151 */
2152 function logout() {
2153 global $wgUser;
2154 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2155 $this->doLogout();
2156 }
2157 }
2158
2159 /**
2160 * Really logout user
2161 * Clears the cookies and session, resets the instance cache
2162 */
2163 function doLogout() {
2164 $this->clearInstanceCache( 'defaults' );
2165
2166 $_SESSION['wsUserID'] = 0;
2167
2168 $this->clearCookie( 'UserID' );
2169 $this->clearCookie( 'Token' );
2170
2171 # Remember when user logged out, to prevent seeing cached pages
2172 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2173 }
2174
2175 /**
2176 * Save object settings into database
2177 * @todo Only rarely do all these fields need to be set!
2178 */
2179 function saveSettings() {
2180 $this->load();
2181 if ( wfReadOnly() ) { return; }
2182 if ( 0 == $this->mId ) { return; }
2183
2184 $this->mTouched = self::newTouchedTimestamp();
2185
2186 $dbw = wfGetDB( DB_MASTER );
2187 $dbw->update( 'user',
2188 array( /* SET */
2189 'user_name' => $this->mName,
2190 'user_password' => $this->mPassword,
2191 'user_newpassword' => $this->mNewpassword,
2192 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2193 'user_real_name' => $this->mRealName,
2194 'user_email' => $this->mEmail,
2195 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2196 'user_options' => $this->encodeOptions(),
2197 'user_touched' => $dbw->timestamp($this->mTouched),
2198 'user_token' => $this->mToken,
2199 'user_email_token' => $this->mEmailToken,
2200 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2201 ), array( /* WHERE */
2202 'user_id' => $this->mId
2203 ), __METHOD__
2204 );
2205 wfRunHooks( 'UserSaveSettings', array( $this ) );
2206 $this->clearSharedCache();
2207 }
2208
2209 /**
2210 * Checks if a user with the given name exists, returns the ID.
2211 */
2212 function idForName() {
2213 $s = trim( $this->getName() );
2214 if ( $s === '' ) return 0;
2215
2216 $dbr = wfGetDB( DB_SLAVE );
2217 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2218 if ( $id === false ) {
2219 $id = 0;
2220 }
2221 return $id;
2222 }
2223
2224 /**
2225 * Add a user to the database, return the user object
2226 *
2227 * @param string $name The user's name
2228 * @param array $params Associative array of non-default parameters to save to the database:
2229 * password The user's password. Password logins will be disabled if this is omitted.
2230 * newpassword A temporary password mailed to the user
2231 * email The user's email address
2232 * email_authenticated The email authentication timestamp
2233 * real_name The user's real name
2234 * options An associative array of non-default options
2235 * token Random authentication token. Do not set.
2236 * registration Registration timestamp. Do not set.
2237 *
2238 * @return User object, or null if the username already exists
2239 */
2240 static function createNew( $name, $params = array() ) {
2241 $user = new User;
2242 $user->load();
2243 if ( isset( $params['options'] ) ) {
2244 $user->mOptions = $params['options'] + $user->mOptions;
2245 unset( $params['options'] );
2246 }
2247 $dbw = wfGetDB( DB_MASTER );
2248 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2249 $fields = array(
2250 'user_id' => $seqVal,
2251 'user_name' => $name,
2252 'user_password' => $user->mPassword,
2253 'user_newpassword' => $user->mNewpassword,
2254 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2255 'user_email' => $user->mEmail,
2256 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2257 'user_real_name' => $user->mRealName,
2258 'user_options' => $user->encodeOptions(),
2259 'user_token' => $user->mToken,
2260 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2261 'user_editcount' => 0,
2262 );
2263 foreach ( $params as $name => $value ) {
2264 $fields["user_$name"] = $value;
2265 }
2266 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2267 if ( $dbw->affectedRows() ) {
2268 $newUser = User::newFromId( $dbw->insertId() );
2269 } else {
2270 $newUser = null;
2271 }
2272 return $newUser;
2273 }
2274
2275 /**
2276 * Add an existing user object to the database
2277 */
2278 function addToDatabase() {
2279 $this->load();
2280 $dbw = wfGetDB( DB_MASTER );
2281 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2282 $dbw->insert( 'user',
2283 array(
2284 'user_id' => $seqVal,
2285 'user_name' => $this->mName,
2286 'user_password' => $this->mPassword,
2287 'user_newpassword' => $this->mNewpassword,
2288 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2289 'user_email' => $this->mEmail,
2290 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2291 'user_real_name' => $this->mRealName,
2292 'user_options' => $this->encodeOptions(),
2293 'user_token' => $this->mToken,
2294 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2295 'user_editcount' => 0,
2296 ), __METHOD__
2297 );
2298 $this->mId = $dbw->insertId();
2299
2300 # Clear instance cache other than user table data, which is already accurate
2301 $this->clearInstanceCache();
2302 }
2303
2304 /**
2305 * If the (non-anonymous) user is blocked, this function will block any IP address
2306 * that they successfully log on from.
2307 */
2308 function spreadBlock() {
2309 wfDebug( __METHOD__."()\n" );
2310 $this->load();
2311 if ( $this->mId == 0 ) {
2312 return;
2313 }
2314
2315 $userblock = Block::newFromDB( '', $this->mId );
2316 if ( !$userblock ) {
2317 return;
2318 }
2319
2320 $userblock->doAutoblock( wfGetIp() );
2321
2322 }
2323
2324 /**
2325 * Generate a string which will be different for any combination of
2326 * user options which would produce different parser output.
2327 * This will be used as part of the hash key for the parser cache,
2328 * so users will the same options can share the same cached data
2329 * safely.
2330 *
2331 * Extensions which require it should install 'PageRenderingHash' hook,
2332 * which will give them a chance to modify this key based on their own
2333 * settings.
2334 *
2335 * @return string
2336 */
2337 function getPageRenderingHash() {
2338 global $wgContLang, $wgUseDynamicDates, $wgLang;
2339 if( $this->mHash ){
2340 return $this->mHash;
2341 }
2342
2343 // stubthreshold is only included below for completeness,
2344 // it will always be 0 when this function is called by parsercache.
2345
2346 $confstr = $this->getOption( 'math' );
2347 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2348 if ( $wgUseDynamicDates ) {
2349 $confstr .= '!' . $this->getDatePreference();
2350 }
2351 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2352 $confstr .= '!' . $wgLang->getCode();
2353 $confstr .= '!' . $this->getOption( 'thumbsize' );
2354 // add in language specific options, if any
2355 $extra = $wgContLang->getExtraHashOptions();
2356 $confstr .= $extra;
2357
2358 // Give a chance for extensions to modify the hash, if they have
2359 // extra options or other effects on the parser cache.
2360 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2361
2362 // Make it a valid memcached key fragment
2363 $confstr = str_replace( ' ', '_', $confstr );
2364 $this->mHash = $confstr;
2365 return $confstr;
2366 }
2367
2368 function isBlockedFromCreateAccount() {
2369 $this->getBlockedStatus();
2370 return $this->mBlock && $this->mBlock->mCreateAccount;
2371 }
2372
2373 /**
2374 * Determine if the user is blocked from using Special:Emailuser.
2375 *
2376 * @public
2377 * @return boolean
2378 */
2379 function isBlockedFromEmailuser() {
2380 $this->getBlockedStatus();
2381 return $this->mBlock && $this->mBlock->mBlockEmail;
2382 }
2383
2384 function isAllowedToCreateAccount() {
2385 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2386 }
2387
2388 /**
2389 * @deprecated
2390 */
2391 function setLoaded( $loaded ) {
2392 wfDeprecated( __METHOD__ );
2393 }
2394
2395 /**
2396 * Get this user's personal page title.
2397 *
2398 * @return Title
2399 * @public
2400 */
2401 function getUserPage() {
2402 return Title::makeTitle( NS_USER, $this->getName() );
2403 }
2404
2405 /**
2406 * Get this user's talk page title.
2407 *
2408 * @return Title
2409 * @public
2410 */
2411 function getTalkPage() {
2412 $title = $this->getUserPage();
2413 return $title->getTalkPage();
2414 }
2415
2416 /**
2417 * @static
2418 */
2419 function getMaxID() {
2420 static $res; // cache
2421
2422 if ( isset( $res ) )
2423 return $res;
2424 else {
2425 $dbr = wfGetDB( DB_SLAVE );
2426 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2427 }
2428 }
2429
2430 /**
2431 * Determine whether the user is a newbie. Newbies are either
2432 * anonymous IPs, or the most recently created accounts.
2433 * @return bool True if it is a newbie.
2434 */
2435 function isNewbie() {
2436 return !$this->isAllowed( 'autoconfirmed' );
2437 }
2438
2439 /**
2440 * Is the user active? We check to see if they've made at least
2441 * X number of edits in the last Y days.
2442 *
2443 * @return bool true if the user is active, false if not
2444 */
2445 public function isActiveEditor() {
2446 global $wgActiveUserEditCount, $wgActiveUserDays;
2447 $dbr = wfGetDB( DB_SLAVE );
2448
2449 // Stolen without shame from RC
2450 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2451 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2452 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2453
2454 $res = $dbr->select( 'revision', '1',
2455 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2456 __METHOD__,
2457 array('LIMIT' => $wgActiveUserEditCount ) );
2458
2459 $count = $dbr->numRows($res);
2460 $dbr->freeResult($res);
2461
2462 return $count == $wgActiveUserEditCount;
2463 }
2464
2465 /**
2466 * Check to see if the given clear-text password is one of the accepted passwords
2467 * @param string $password User password.
2468 * @return bool True if the given password is correct otherwise False.
2469 */
2470 function checkPassword( $password ) {
2471 global $wgAuth;
2472 $this->load();
2473
2474 // Even though we stop people from creating passwords that
2475 // are shorter than this, doesn't mean people wont be able
2476 // to. Certain authentication plugins do NOT want to save
2477 // domain passwords in a mysql database, so we should
2478 // check this (incase $wgAuth->strict() is false).
2479 if( !$this->isValidPassword( $password ) ) {
2480 return false;
2481 }
2482
2483 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2484 return true;
2485 } elseif( $wgAuth->strict() ) {
2486 /* Auth plugin doesn't allow local authentication */
2487 return false;
2488 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2489 /* Auth plugin doesn't allow local authentication for this user name */
2490 return false;
2491 }
2492 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2493 return true;
2494 } elseif ( function_exists( 'iconv' ) ) {
2495 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2496 # Check for this with iconv
2497 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2498 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2499 return true;
2500 }
2501 }
2502 return false;
2503 }
2504
2505 /**
2506 * Check if the given clear-text password matches the temporary password
2507 * sent by e-mail for password reset operations.
2508 * @return bool
2509 */
2510 function checkTemporaryPassword( $plaintext ) {
2511 return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() );
2512 }
2513
2514 /**
2515 * Initialize (if necessary) and return a session token value
2516 * which can be used in edit forms to show that the user's
2517 * login credentials aren't being hijacked with a foreign form
2518 * submission.
2519 *
2520 * @param mixed $salt - Optional function-specific data for hash.
2521 * Use a string or an array of strings.
2522 * @return string
2523 * @public
2524 */
2525 function editToken( $salt = '' ) {
2526 if ( $this->isAnon() ) {
2527 return EDIT_TOKEN_SUFFIX;
2528 } else {
2529 if( !isset( $_SESSION['wsEditToken'] ) ) {
2530 $token = $this->generateToken();
2531 $_SESSION['wsEditToken'] = $token;
2532 } else {
2533 $token = $_SESSION['wsEditToken'];
2534 }
2535 if( is_array( $salt ) ) {
2536 $salt = implode( '|', $salt );
2537 }
2538 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2539 }
2540 }
2541
2542 /**
2543 * Generate a hex-y looking random token for various uses.
2544 * Could be made more cryptographically sure if someone cares.
2545 * @return string
2546 */
2547 function generateToken( $salt = '' ) {
2548 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2549 return md5( $token . $salt );
2550 }
2551
2552 /**
2553 * Check given value against the token value stored in the session.
2554 * A match should confirm that the form was submitted from the
2555 * user's own login session, not a form submission from a third-party
2556 * site.
2557 *
2558 * @param string $val - the input value to compare
2559 * @param string $salt - Optional function-specific data for hash
2560 * @return bool
2561 * @public
2562 */
2563 function matchEditToken( $val, $salt = '' ) {
2564 $sessionToken = $this->editToken( $salt );
2565 if ( $val != $sessionToken ) {
2566 wfDebug( "User::matchEditToken: broken session data\n" );
2567 }
2568 return $val == $sessionToken;
2569 }
2570
2571 /**
2572 * Check whether the edit token is fine except for the suffix
2573 */
2574 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2575 $sessionToken = $this->editToken( $salt );
2576 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2577 }
2578
2579 /**
2580 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2581 * mail to the user's given address.
2582 *
2583 * Calls saveSettings() internally; as it has side effects, not committing changes
2584 * would be pretty silly.
2585 *
2586 * @return mixed True on success, a WikiError object on failure.
2587 */
2588 function sendConfirmationMail() {
2589 global $wgLang;
2590 $expiration = null; // gets passed-by-ref and defined in next line.
2591 $token = $this->confirmationToken( $expiration );
2592 $url = $this->confirmationTokenUrl( $token );
2593 $invalidateURL = $this->invalidationTokenUrl( $token );
2594 $this->saveSettings();
2595
2596 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2597 wfMsg( 'confirmemail_body',
2598 wfGetIP(),
2599 $this->getName(),
2600 $url,
2601 $wgLang->timeanddate( $expiration, false ),
2602 $invalidateURL ) );
2603 }
2604
2605 /**
2606 * Send an e-mail to this user's account. Does not check for
2607 * confirmed status or validity.
2608 *
2609 * @param string $subject
2610 * @param string $body
2611 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2612 * @return mixed True on success, a WikiError object on failure.
2613 */
2614 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2615 if( is_null( $from ) ) {
2616 global $wgPasswordSender;
2617 $from = $wgPasswordSender;
2618 }
2619
2620 $to = new MailAddress( $this );
2621 $sender = new MailAddress( $from );
2622 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2623 }
2624
2625 /**
2626 * Generate, store, and return a new e-mail confirmation code.
2627 * A hash (unsalted since it's used as a key) is stored.
2628 *
2629 * Call saveSettings() after calling this function to commit
2630 * this change to the database.
2631 *
2632 * @param &$expiration mixed output: accepts the expiration time
2633 * @return string
2634 * @private
2635 */
2636 function confirmationToken( &$expiration ) {
2637 $now = time();
2638 $expires = $now + 7 * 24 * 60 * 60;
2639 $expiration = wfTimestamp( TS_MW, $expires );
2640 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2641 $hash = md5( $token );
2642 $this->load();
2643 $this->mEmailToken = $hash;
2644 $this->mEmailTokenExpires = $expiration;
2645 return $token;
2646 }
2647
2648 /**
2649 * Return a URL the user can use to confirm their email address.
2650 * @param $token: accepts the email confirmation token
2651 * @return string
2652 * @private
2653 */
2654 function confirmationTokenUrl( $token ) {
2655 return $this->getTokenUrl( 'ConfirmEmail', $token );
2656 }
2657 /**
2658 * Return a URL the user can use to invalidate their email address.
2659 * @param $token: accepts the email confirmation token
2660 * @return string
2661 * @private
2662 */
2663 function invalidationTokenUrl( $token ) {
2664 return $this->getTokenUrl( 'Invalidateemail', $token );
2665 }
2666
2667 /**
2668 * Internal function to format the e-mail validation/invalidation URLs.
2669 * This uses $wgArticlePath directly as a quickie hack to use the
2670 * hardcoded English names of the Special: pages, for ASCII safety.
2671 *
2672 * Since these URLs get dropped directly into emails, using the
2673 * short English names avoids insanely long URL-encoded links, which
2674 * also sometimes can get corrupted in some browsers/mailers
2675 * (bug 6957 with Gmail and Internet Explorer).
2676 */
2677 protected function getTokenUrl( $page, $token ) {
2678 global $wgArticlePath;
2679 return wfExpandUrl(
2680 str_replace(
2681 '$1',
2682 "Special:$page/$token",
2683 $wgArticlePath ) );
2684 }
2685
2686 /**
2687 * Mark the e-mail address confirmed.
2688 *
2689 * Call saveSettings() after calling this function to commit the change.
2690 */
2691 function confirmEmail() {
2692 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2693 return true;
2694 }
2695
2696 /**
2697 * Invalidate the user's email confirmation, unauthenticate the email
2698 * if it was already confirmed.
2699 *
2700 * Call saveSettings() after calling this function to commit the change.
2701 */
2702 function invalidateEmail() {
2703 $this->load();
2704 $this->mEmailToken = null;
2705 $this->mEmailTokenExpires = null;
2706 $this->setEmailAuthenticationTimestamp( null );
2707 return true;
2708 }
2709
2710 function setEmailAuthenticationTimestamp( $timestamp ) {
2711 $this->load();
2712 $this->mEmailAuthenticated = $timestamp;
2713 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2714 }
2715
2716 /**
2717 * Is this user allowed to send e-mails within limits of current
2718 * site configuration?
2719 * @return bool
2720 */
2721 function canSendEmail() {
2722 $canSend = $this->isEmailConfirmed();
2723 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2724 return $canSend;
2725 }
2726
2727 /**
2728 * Is this user allowed to receive e-mails within limits of current
2729 * site configuration?
2730 * @return bool
2731 */
2732 function canReceiveEmail() {
2733 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2734 }
2735
2736 /**
2737 * Is this user's e-mail address valid-looking and confirmed within
2738 * limits of the current site configuration?
2739 *
2740 * If $wgEmailAuthentication is on, this may require the user to have
2741 * confirmed their address by returning a code or using a password
2742 * sent to the address from the wiki.
2743 *
2744 * @return bool
2745 */
2746 function isEmailConfirmed() {
2747 global $wgEmailAuthentication;
2748 $this->load();
2749 $confirmed = true;
2750 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2751 if( $this->isAnon() )
2752 return false;
2753 if( !self::isValidEmailAddr( $this->mEmail ) )
2754 return false;
2755 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2756 return false;
2757 return true;
2758 } else {
2759 return $confirmed;
2760 }
2761 }
2762
2763 /**
2764 * Return true if there is an outstanding request for e-mail confirmation.
2765 * @return bool
2766 */
2767 function isEmailConfirmationPending() {
2768 global $wgEmailAuthentication;
2769 return $wgEmailAuthentication &&
2770 !$this->isEmailConfirmed() &&
2771 $this->mEmailToken &&
2772 $this->mEmailTokenExpires > wfTimestamp();
2773 }
2774
2775 /**
2776 * Get the timestamp of account creation, or false for
2777 * non-existent/anonymous user accounts
2778 *
2779 * @return mixed
2780 */
2781 public function getRegistration() {
2782 return $this->mId > 0
2783 ? $this->mRegistration
2784 : false;
2785 }
2786
2787 /**
2788 * @param array $groups list of groups
2789 * @return array list of permission key names for given groups combined
2790 */
2791 static function getGroupPermissions( $groups ) {
2792 global $wgGroupPermissions;
2793 $rights = array();
2794 foreach( $groups as $group ) {
2795 if( isset( $wgGroupPermissions[$group] ) ) {
2796 $rights = array_merge( $rights,
2797 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2798 }
2799 }
2800 return $rights;
2801 }
2802
2803 /**
2804 * @param string $group key name
2805 * @return string localized descriptive name for group, if provided
2806 */
2807 static function getGroupName( $group ) {
2808 global $wgMessageCache;
2809 $wgMessageCache->loadAllMessages();
2810 $key = "group-$group";
2811 $name = wfMsg( $key );
2812 return $name == '' || wfEmptyMsg( $key, $name )
2813 ? $group
2814 : $name;
2815 }
2816
2817 /**
2818 * @param string $group key name
2819 * @return string localized descriptive name for member of a group, if provided
2820 */
2821 static function getGroupMember( $group ) {
2822 global $wgMessageCache;
2823 $wgMessageCache->loadAllMessages();
2824 $key = "group-$group-member";
2825 $name = wfMsg( $key );
2826 return $name == '' || wfEmptyMsg( $key, $name )
2827 ? $group
2828 : $name;
2829 }
2830
2831 /**
2832 * Return the set of defined explicit groups.
2833 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2834 * are not included, as they are defined automatically,
2835 * not in the database.
2836 * @return array
2837 */
2838 static function getAllGroups() {
2839 global $wgGroupPermissions;
2840 return array_diff(
2841 array_keys( $wgGroupPermissions ),
2842 self::getImplicitGroups()
2843 );
2844 }
2845
2846 /**
2847 * Get a list of all available permissions
2848 */
2849 static function getAllRights() {
2850 if ( self::$mAllRights === false ) {
2851 global $wgAvailableRights;
2852 if ( count( $wgAvailableRights ) ) {
2853 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
2854 } else {
2855 self::$mAllRights = self::$mCoreRights;
2856 }
2857 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
2858 }
2859 return self::$mAllRights;
2860 }
2861
2862 /**
2863 * Get a list of implicit groups
2864 *
2865 * @return array
2866 */
2867 public static function getImplicitGroups() {
2868 global $wgImplicitGroups;
2869 $groups = $wgImplicitGroups;
2870 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2871 return $groups;
2872 }
2873
2874 /**
2875 * Get the title of a page describing a particular group
2876 *
2877 * @param $group Name of the group
2878 * @return mixed
2879 */
2880 static function getGroupPage( $group ) {
2881 global $wgMessageCache;
2882 $wgMessageCache->loadAllMessages();
2883 $page = wfMsgForContent( 'grouppage-' . $group );
2884 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2885 $title = Title::newFromText( $page );
2886 if( is_object( $title ) )
2887 return $title;
2888 }
2889 return false;
2890 }
2891
2892 /**
2893 * Create a link to the group in HTML, if available
2894 *
2895 * @param $group Name of the group
2896 * @param $text The text of the link
2897 * @return mixed
2898 */
2899 static function makeGroupLinkHTML( $group, $text = '' ) {
2900 if( $text == '' ) {
2901 $text = self::getGroupName( $group );
2902 }
2903 $title = self::getGroupPage( $group );
2904 if( $title ) {
2905 global $wgUser;
2906 $sk = $wgUser->getSkin();
2907 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2908 } else {
2909 return $text;
2910 }
2911 }
2912
2913 /**
2914 * Create a link to the group in Wikitext, if available
2915 *
2916 * @param $group Name of the group
2917 * @param $text The text of the link (by default, the name of the group)
2918 * @return mixed
2919 */
2920 static function makeGroupLinkWiki( $group, $text = '' ) {
2921 if( $text == '' ) {
2922 $text = self::getGroupName( $group );
2923 }
2924 $title = self::getGroupPage( $group );
2925 if( $title ) {
2926 $page = $title->getPrefixedText();
2927 return "[[$page|$text]]";
2928 } else {
2929 return $text;
2930 }
2931 }
2932
2933 /**
2934 * Increment the user's edit-count field.
2935 * Will have no effect for anonymous users.
2936 */
2937 function incEditCount() {
2938 if( !$this->isAnon() ) {
2939 $dbw = wfGetDB( DB_MASTER );
2940 $dbw->update( 'user',
2941 array( 'user_editcount=user_editcount+1' ),
2942 array( 'user_id' => $this->getId() ),
2943 __METHOD__ );
2944
2945 // Lazy initialization check...
2946 if( $dbw->affectedRows() == 0 ) {
2947 // Pull from a slave to be less cruel to servers
2948 // Accuracy isn't the point anyway here
2949 $dbr = wfGetDB( DB_SLAVE );
2950 $count = $dbr->selectField( 'revision',
2951 'COUNT(rev_user)',
2952 array( 'rev_user' => $this->getId() ),
2953 __METHOD__ );
2954
2955 // Now here's a goddamn hack...
2956 if( $dbr !== $dbw ) {
2957 // If we actually have a slave server, the count is
2958 // at least one behind because the current transaction
2959 // has not been committed and replicated.
2960 $count++;
2961 } else {
2962 // But if DB_SLAVE is selecting the master, then the
2963 // count we just read includes the revision that was
2964 // just added in the working transaction.
2965 }
2966
2967 $dbw->update( 'user',
2968 array( 'user_editcount' => $count ),
2969 array( 'user_id' => $this->getId() ),
2970 __METHOD__ );
2971 }
2972 }
2973 // edit count in user cache too
2974 $this->invalidateCache();
2975 }
2976
2977 static function getRightDescription( $right ) {
2978 global $wgMessageCache;
2979 $wgMessageCache->loadAllMessages();
2980 $key = "right-$right";
2981 $name = wfMsg( $key );
2982 return $name == '' || wfEmptyMsg( $key, $name )
2983 ? $right
2984 : $name;
2985 }
2986
2987 /**
2988 * Make an old-style password hash
2989 *
2990 * @param string $password Plain-text password
2991 * @param string $userId User ID
2992 */
2993 static function oldCrypt( $password, $userId ) {
2994 global $wgPasswordSalt;
2995 if ( $wgPasswordSalt ) {
2996 return md5( $userId . '-' . md5( $password ) );
2997 } else {
2998 return md5( $password );
2999 }
3000 }
3001
3002 /**
3003 * Make a new-style password hash
3004 *
3005 * @param string $password Plain-text password
3006 * @param string $salt Salt, may be random or the user ID. False to generate a salt.
3007 */
3008 static function crypt( $password, $salt = false ) {
3009 global $wgPasswordSalt;
3010
3011 if($wgPasswordSalt) {
3012 if ( $salt === false ) {
3013 $salt = substr( wfGenerateToken(), 0, 8 );
3014 }
3015 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3016 } else {
3017 return ':A:' . md5( $password);
3018 }
3019 }
3020
3021 /**
3022 * Compare a password hash with a plain-text password. Requires the user
3023 * ID if there's a chance that the hash is an old-style hash.
3024 *
3025 * @param string $hash Password hash
3026 * @param string $password Plain-text password to compare
3027 * @param string $userId User ID for old-style password salt
3028 */
3029 static function comparePasswords( $hash, $password, $userId = false ) {
3030 $m = false;
3031 $type = substr( $hash, 0, 3 );
3032 if ( $type == ':A:' ) {
3033 # Unsalted
3034 return md5( $password ) === substr( $hash, 3 );
3035 } elseif ( $type == ':B:' ) {
3036 # Salted
3037 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3038 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3039 } else {
3040 # Old-style
3041 return self::oldCrypt( $password, $userId ) === $hash;
3042 }
3043 }
3044 }