remove typo extra line
[mediawiki.git] / includes / User.php
bloba116389938a832db7130ce3a6e3db7714031ffce
1 <?php
2 /**
3 * See user.doc
5 * @package MediaWiki
6 */
8 /**
11 require_once( 'WatchedItem.php' );
12 require_once( 'Group.php' );
14 # Number of characters in user_token field
15 define( 'USER_TOKEN_LENGTH', 32 );
17 /**
19 * @package MediaWiki
21 class User {
22 /**#@+
23 * @access private
25 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
26 var $mEmailAuthenticationtimestamp;
27 var $mRights, $mOptions;
28 var $mDataLoaded, $mNewpassword;
29 var $mSkin;
30 var $mBlockedby, $mBlockreason;
31 var $mTouched;
32 var $mToken;
33 var $mRealName;
34 var $mHash;
35 /** Array of group id the user belong to */
36 var $mGroups;
37 /**#@-*/
39 /** Construct using User:loadDefaults() */
40 function User() {
41 $this->loadDefaults();
44 /**
45 * Static factory method
46 * @static
47 * @param string $name Username, validated by Title:newFromText()
49 function newFromName( $name ) {
50 $u = new User();
52 # Clean up name according to title rules
54 $t = Title::newFromText( $name );
55 if( is_null( $t ) ) {
56 return NULL;
57 } else {
58 $u->setName( $t->getText() );
59 $u->setId( $u->idFromName( $t->getText() ) );
60 return $u;
64 /**
65 * Get username given an id.
66 * @param integer $id Database user id
67 * @return string Nickname of a user
68 * @static
70 function whoIs( $id ) {
71 $dbr =& wfGetDB( DB_SLAVE );
72 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
75 /**
76 * Get real username given an id.
77 * @param integer $id Database user id
78 * @return string Realname of a user
79 * @static
81 function whoIsReal( $id ) {
82 $dbr =& wfGetDB( DB_SLAVE );
83 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
86 /**
87 * Get database id given a user name
88 * @param string $name Nickname of a user
89 * @return integer|null Database user id (null: if non existent
90 * @static
92 function idFromName( $name ) {
93 $fname = "User::idFromName";
95 $nt = Title::newFromText( $name );
96 if( is_null( $nt ) ) {
97 # Illegal name
98 return null;
100 $dbr =& wfGetDB( DB_SLAVE );
101 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
103 if ( $s === false ) {
104 return 0;
105 } else {
106 return $s->user_id;
111 * does the string match an anonymous user IP address?
112 * @param string $name Nickname of a user
113 * @static
115 function isIP( $name ) {
116 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
120 * does the string match roughly an email address ?
121 * @param string $addr email address
122 * @static
124 function isValidEmailAddr ( $addr ) {
125 return preg_match( '/^([a-z0-9_.-]+([a-z0-9_.-]+)*\@[a-z0-9_-]+([a-z0-9_.-]+)*([a-z.]{2,})+)$/', strtolower($addr));
129 * probably return a random password
130 * @return string probably a random password
131 * @static
132 * @todo Check what is doing really [AV]
134 function randomPassword() {
135 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
136 $l = strlen( $pwchars ) - 1;
138 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
139 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
140 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
141 $pwchars{mt_rand( 0, $l )};
142 return $np;
146 * Set properties to default
147 * Used at construction. It will load per language default settings only
148 * if we have an available language object.
150 function loadDefaults() {
151 static $n=0;
152 $n++;
153 $fname = 'User::loadDefaults' . $n;
154 wfProfileIn( $fname );
156 global $wgContLang, $wgIP, $wgDBname;
157 global $wgNamespacesToBeSearchedDefault;
159 $this->mId = 0;
160 $this->mNewtalk = -1;
161 $this->mName = $wgIP;
162 $this->mRealName = $this->mEmail = '';
163 $this->mEmailAuthenticationtimestamp = 0;
164 $this->mPassword = $this->mNewpassword = '';
165 $this->mRights = array();
166 $this->mGroups = array();
167 // Getting user defaults only if we have an available language
168 if( isset( $wgContLang ) ) {
169 $this->loadDefaultFromLanguage();
172 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
173 $this->mOptions['searchNs'.$nsnum] = $val;
175 unset( $this->mSkin );
176 $this->mDataLoaded = false;
177 $this->mBlockedby = -1; # Unset
178 $this->setToken(); # Random
179 $this->mHash = false;
181 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
182 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
184 else {
185 $this->mTouched = '0'; # Allow any pages to be cached
188 wfProfileOut( $fname );
192 * Used to load user options from a language.
193 * This is not in loadDefault() cause we sometime create user before having
194 * a language object.
196 function loadDefaultFromLanguage(){
197 $this->mOptions = User::getDefaultOptions();
201 * Combine the language default options with any site-specific options
202 * and add the default language variants.
204 * @return array
205 * @static
206 * @access private
208 function getDefaultOptions() {
210 * Site defaults will override the global/language defaults
212 global $wgContLang, $wgDefaultUserOptions;
213 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
216 * default language setting
218 $variant = $wgContLang->getPreferredVariant();
219 $defOpt['variant'] = $variant;
220 $defOpt['language'] = $variant;
222 return $defOpt;
226 * Get a given default option value.
228 * @param string $opt
229 * @return string
230 * @static
231 * @access public
233 function getDefaultOption( $opt ) {
234 $defOpts = User::getDefaultOptions();
235 if( isset( $defOpts[$opt] ) ) {
236 return $defOpts[$opt];
237 } else {
238 return '';
243 * Get blocking information
244 * @access private
246 function getBlockedStatus() {
247 global $wgIP, $wgBlockCache, $wgProxyList;
249 if ( -1 != $this->mBlockedby ) { return; }
251 $this->mBlockedby = 0;
253 # User blocking
254 if ( $this->mId ) {
255 $block = new Block();
256 if ( $block->load( $wgIP , $this->mId ) ) {
257 $this->mBlockedby = $block->mBy;
258 $this->mBlockreason = $block->mReason;
262 # IP/range blocking
263 if ( !$this->mBlockedby ) {
264 $block = $wgBlockCache->get( $wgIP );
265 if ( $block !== false ) {
266 $this->mBlockedby = $block->mBy;
267 $this->mBlockreason = $block->mReason;
271 # Proxy blocking
272 if ( !$this->mBlockedby ) {
273 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
274 $this->mBlockedby = wfMsg( 'proxyblocker' );
275 $this->mBlockreason = wfMsg( 'proxyblockreason' );
281 * Check if user is blocked
282 * @return bool True if blocked, false otherwise
284 function isBlocked() {
285 $this->getBlockedStatus();
286 if ( 0 === $this->mBlockedby ) { return false; }
287 return true;
291 * Get name of blocker
292 * @return string name of blocker
294 function blockedBy() {
295 $this->getBlockedStatus();
296 return $this->mBlockedby;
300 * Get blocking reason
301 * @return string Blocking reason
303 function blockedFor() {
304 $this->getBlockedStatus();
305 return $this->mBlockreason;
309 * Initialise php session
311 function SetupSession() {
312 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
313 if( $wgSessionsInMemcached ) {
314 require_once( 'MemcachedSessions.php' );
315 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
316 # If it's left on 'user' or another setting from another
317 # application, it will end up failing. Try to recover.
318 ini_set ( 'session.save_handler', 'files' );
320 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
321 session_cache_limiter( 'private, must-revalidate' );
322 @session_start();
326 * Read datas from session
327 * @static
329 function loadFromSession() {
330 global $wgMemc, $wgDBname;
332 if ( isset( $_SESSION['wsUserID'] ) ) {
333 if ( 0 != $_SESSION['wsUserID'] ) {
334 $sId = $_SESSION['wsUserID'];
335 } else {
336 return new User();
338 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
339 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
340 $_SESSION['wsUserID'] = $sId;
341 } else {
342 return new User();
344 if ( isset( $_SESSION['wsUserName'] ) ) {
345 $sName = $_SESSION['wsUserName'];
346 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
347 $sName = $_COOKIE["{$wgDBname}UserName"];
348 $_SESSION['wsUserName'] = $sName;
349 } else {
350 return new User();
353 $passwordCorrect = FALSE;
354 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
355 if($makenew = !$user) {
356 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
357 $user = new User();
358 $user->mId = $sId;
359 $user->loadFromDatabase();
360 } else {
361 wfDebug( "User::loadFromSession() got from cache!\n" );
364 if ( isset( $_SESSION['wsToken'] ) ) {
365 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
366 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
367 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
368 } else {
369 return new User(); # Can't log in from session
372 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
373 if($makenew) {
374 if($wgMemc->set( $key, $user ))
375 wfDebug( "User::loadFromSession() successfully saved user\n" );
376 else
377 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
379 $user->spreadBlock();
380 return $user;
382 return new User(); # Can't log in from session
386 * Load a user from the database
388 function loadFromDatabase() {
389 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
390 $fname = "User::loadFromDatabase";
392 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
393 # loading in a command line script, don't assume all command line scripts need it like this
394 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
395 if ( $this->mDataLoaded ) {
396 return;
399 # Paranoia
400 $this->mId = IntVal( $this->mId );
402 /** Anonymous user */
403 if(!$this->mId) {
404 /** Get rights */
405 $anong = Group::newFromId($wgAnonGroupId);
406 if (!$anong)
407 wfDebugDieBacktrace("Please update your database schema "
408 ."and populate initial group data from "
409 ."maintenance/archives patches");
410 $anong->loadFromDatabase();
411 $this->mRights = explode(',', $anong->getRights());
412 $this->mDataLoaded = true;
413 return;
414 } # the following stuff is for non-anonymous users only
416 $dbr =& wfGetDB( DB_SLAVE );
417 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
418 'user_emailauthenticationtimestamp',
419 'user_real_name','user_options','user_touched', 'user_token' ),
420 array( 'user_id' => $this->mId ), $fname );
422 if ( $s !== false ) {
423 $this->mName = $s->user_name;
424 $this->mEmail = $s->user_email;
425 $this->mEmailAuthenticationtimestamp = wfTimestamp(TS_MW,$s->user_emailauthenticationtimestamp);
426 $this->mRealName = $s->user_real_name;
427 $this->mPassword = $s->user_password;
428 $this->mNewpassword = $s->user_newpassword;
429 $this->decodeOptions( $s->user_options );
430 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
431 $this->mToken = $s->user_token;
433 // Get groups id
434 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
436 while($group = $dbr->fetchRow($res)) {
437 $this->mGroups[] = $group[0];
440 // add the default group for logged in user
441 $this->mGroups[] = $wgLoggedInGroupId;
443 $this->mRights = array();
444 // now we merge groups rights to get this user rights
445 foreach($this->mGroups as $aGroupId) {
446 $g = Group::newFromId($aGroupId);
447 $g->loadFromDatabase();
448 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
451 // array merge duplicate rights which are part of several groups
452 $this->mRights = array_unique($this->mRights);
454 $dbr->freeResult($res);
457 $this->mDataLoaded = true;
460 function getID() { return $this->mId; }
461 function setID( $v ) {
462 $this->mId = $v;
463 $this->mDataLoaded = false;
466 function getName() {
467 $this->loadFromDatabase();
468 return $this->mName;
471 function setName( $str ) {
472 $this->loadFromDatabase();
473 $this->mName = $str;
478 * Return the title dbkey form of the name, for eg user pages.
479 * @return string
480 * @access public
482 function getTitleKey() {
483 return str_replace( ' ', '_', $this->getName() );
486 function getNewtalk() {
487 $fname = 'User::getNewtalk';
488 $this->loadFromDatabase();
490 # Load the newtalk status if it is unloaded (mNewtalk=-1)
491 if( $this->mNewtalk == -1 ) {
492 $this->mNewtalk = 0; # reset talk page status
494 # Check memcached separately for anons, who have no
495 # entire User object stored in there.
496 if( !$this->mId ) {
497 global $wgDBname, $wgMemc;
498 $key = "$wgDBname:newtalk:ip:{$this->mName}";
499 $newtalk = $wgMemc->get( $key );
500 if( is_integer( $newtalk ) ) {
501 $this->mNewtalk = $newtalk ? 1 : 0;
502 return (bool)$this->mNewtalk;
506 $dbr =& wfGetDB( DB_SLAVE );
507 $res = $dbr->select( 'watchlist',
508 array( 'wl_user' ),
509 array( 'wl_title' => $this->getTitleKey(),
510 'wl_namespace' => NS_USER_TALK,
511 'wl_user' => $this->mId,
512 'wl_notificationtimestamp != 0' ),
513 'User::getNewtalk' );
514 if( $dbr->numRows($res) > 0 ) {
515 $this->mNewtalk = 1;
517 $dbr->freeResult( $res );
519 if( !$this->mId ) {
520 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
524 return ( 0 != $this->mNewtalk );
527 function setNewtalk( $val ) {
528 $this->loadFromDatabase();
529 $this->mNewtalk = $val;
530 $this->invalidateCache();
533 function invalidateCache() {
534 $this->loadFromDatabase();
535 $this->mTouched = wfTimestampNow();
536 # Don't forget to save the options after this or
537 # it won't take effect!
540 function validateCache( $timestamp ) {
541 $this->loadFromDatabase();
542 return ($timestamp >= $this->mTouched);
546 * Salt a password.
547 * Will only be salted if $wgPasswordSalt is true
548 * @param string Password.
549 * @return string Salted password or clear password.
551 function addSalt( $p ) {
552 global $wgPasswordSalt;
553 if($wgPasswordSalt)
554 return md5( "{$this->mId}-{$p}" );
555 else
556 return $p;
560 * Encrypt a password.
561 * It can eventuall salt a password @see User::addSalt()
562 * @param string $p clear Password.
563 * @param string Encrypted password.
565 function encryptPassword( $p ) {
566 return $this->addSalt( md5( $p ) );
569 # Set the password and reset the random token
570 function setPassword( $str ) {
571 $this->loadFromDatabase();
572 $this->setToken();
573 $this->mPassword = $this->encryptPassword( $str );
574 $this->mNewpassword = '';
577 # Set the random token (used for persistent authentication)
578 function setToken( $token = false ) {
579 if ( !$token ) {
580 $this->mToken = '';
581 # Take random data from PRNG
582 # This is reasonably secure if the PRNG has been seeded correctly
583 for ($i = 0; $i<USER_TOKEN_LENGTH / 4; $i++) {
584 $this->mToken .= sprintf( "%04X", mt_rand( 0, 65535 ) );
586 } else {
587 $this->mToken = $token;
592 function setCookiePassword( $str ) {
593 $this->loadFromDatabase();
594 $this->mCookiePassword = md5( $str );
597 function setNewpassword( $str ) {
598 $this->loadFromDatabase();
599 $this->mNewpassword = $this->encryptPassword( $str );
602 function getEmail() {
603 $this->loadFromDatabase();
604 return $this->mEmail;
607 function getEmailAuthenticationtimestamp() {
608 $this->loadFromDatabase();
609 return $this->mEmailAuthenticationtimestamp;
612 function setEmail( $str ) {
613 $this->loadFromDatabase();
614 $this->mEmail = $str;
617 function getRealName() {
618 $this->loadFromDatabase();
619 return $this->mRealName;
622 function setRealName( $str ) {
623 $this->loadFromDatabase();
624 $this->mRealName = $str;
627 function getOption( $oname ) {
628 $this->loadFromDatabase();
629 if ( array_key_exists( $oname, $this->mOptions ) ) {
630 return $this->mOptions[$oname];
631 } else {
632 return '';
636 function setOption( $oname, $val ) {
637 $this->loadFromDatabase();
638 if ( $oname == 'skin' ) {
639 # Clear cached skin, so the new one displays immediately in Special:Preferences
640 unset( $this->mSkin );
642 $this->mOptions[$oname] = $val;
643 $this->invalidateCache();
646 function getRights() {
647 $this->loadFromDatabase();
648 return $this->mRights;
651 function addRight( $rname ) {
652 $this->loadFromDatabase();
653 array_push( $this->mRights, $rname );
654 $this->invalidateCache();
657 function getGroups() {
658 $this->loadFromDatabase();
659 return $this->mGroups;
662 function setGroups($groups) {
663 $this->loadFromDatabase();
664 $this->mGroups = $groups;
665 $this->invalidateCache();
669 * Check if a user is sysop
670 * Die with backtrace. Use User:isAllowed() instead.
671 * @deprecated
673 function isSysop() {
675 $this->loadFromDatabase();
676 if ( 0 == $this->mId ) { return false; }
678 return in_array( 'sysop', $this->mRights );
680 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
683 /** @deprecated */
684 function isDeveloper() {
686 $this->loadFromDatabase();
687 if ( 0 == $this->mId ) { return false; }
689 return in_array( 'developer', $this->mRights );
691 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
694 /** @deprecated */
695 function isBureaucrat() {
697 $this->loadFromDatabase();
698 if ( 0 == $this->mId ) { return false; }
700 return in_array( 'bureaucrat', $this->mRights );
702 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
706 * Whether the user is a bot
707 * @todo need to be migrated to the new user level management sytem
709 function isBot() {
710 $this->loadFromDatabase();
712 # Why was this here? I need a UID=0 conversion script [TS]
713 # if ( 0 == $this->mId ) { return false; }
715 return in_array( 'bot', $this->mRights );
719 * Check if user is allowed to access a feature / make an action
720 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
721 * @return boolean True: action is allowed, False: action should not be allowed
723 function isAllowed($action='') {
724 $this->loadFromDatabase();
725 return in_array( $action , $this->mRights );
729 * Load a skin if it doesn't exist or return it
730 * @todo FIXME : need to check the old failback system [AV]
732 function &getSkin() {
733 global $IP;
734 if ( ! isset( $this->mSkin ) ) {
735 $fname = 'User::getSkin';
736 wfProfileIn( $fname );
738 # get all skin names available
739 $skinNames = Skin::getSkinNames();
741 # get the user skin
742 $userSkin = $this->getOption( 'skin' );
743 if ( $userSkin == '' ) { $userSkin = 'standard'; }
745 if ( !isset( $skinNames[$userSkin] ) ) {
746 # in case the user skin could not be found find a replacement
747 $fallback = array(
748 0 => 'Standard',
749 1 => 'Nostalgia',
750 2 => 'CologneBlue');
751 # if phptal is enabled we should have monobook skin that
752 # superseed the good old SkinStandard.
753 if ( isset( $skinNames['monobook'] ) ) {
754 $fallback[0] = 'MonoBook';
757 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
758 $sn = $fallback[$userSkin];
759 } else {
760 $sn = 'Standard';
762 } else {
763 # The user skin is available
764 $sn = $skinNames[$userSkin];
767 # Grab the skin class and initialise it. Each skin checks for PHPTal
768 # and will not load if it's not enabled.
769 require_once( $IP.'/skins/'.$sn.'.php' );
771 # Check if we got if not failback to default skin
772 $className = 'Skin'.$sn;
773 if( !class_exists( $className ) ) {
774 # DO NOT die if the class isn't found. This breaks maintenance
775 # scripts and can cause a user account to be unrecoverable
776 # except by SQL manipulation if a previously valid skin name
777 # is no longer valid.
778 $className = 'SkinStandard';
779 require_once( $IP.'/skins/Standard.php' );
781 $this->mSkin =& new $className;
782 wfProfileOut( $fname );
784 return $this->mSkin;
787 /**#@+
788 * @param string $title Article title to look at
792 * Check watched status of an article
793 * @return bool True if article is watched
795 function isWatched( $title ) {
796 $wl = WatchedItem::fromUserTitle( $this, $title );
797 return $wl->isWatched();
801 * Watch an article
803 function addWatch( $title ) {
804 $wl = WatchedItem::fromUserTitle( $this, $title );
805 $wl->addWatch();
806 $this->invalidateCache();
810 * Stop watching an article
812 function removeWatch( $title ) {
813 $wl = WatchedItem::fromUserTitle( $this, $title );
814 $wl->removeWatch();
815 $this->invalidateCache();
819 * Clear the user's notification timestamp for the given title.
820 * If e-notif e-mails are on, they will receive notification mails on
821 * the next change of the page if it's watched etc.
823 function clearNotification( $title ) {
824 $userid = $this->getId();
825 if ($userid==0)
826 return;
827 $dbw =& wfGetDB( DB_MASTER );
828 $success = $dbw->update( 'watchlist',
829 array( /* SET */
830 'wl_notificationtimestamp' => $dbw->timestamp(0)
831 ), array( /* WHERE */
832 'wl_title' => $title->getDBkey(),
833 'wl_namespace' => $title->getNamespace(),
834 'wl_user' => $this->getId()
835 ), 'User::clearLastVisited'
839 /**#@-*/
842 * Resets all of the given user's page-change notification timestamps.
843 * If e-notif e-mails are on, they will receive notification mails on
844 * the next change of any watched page.
846 * @param int $currentUser user ID number
847 * @access public
849 function clearAllNotifications( $currentUser ) {
850 if( $currentUser != 0 ) {
852 $dbw =& wfGetDB( DB_MASTER );
853 $success = $dbw->update( 'watchlist',
854 array( /* SET */
855 'wl_notificationtimestamp' => 0
856 ), array( /* WHERE */
857 'wl_user' => $currentUser
858 ), 'UserMailer::clearAll'
861 # we also need to clear here the "you have new message" notification for the own user_talk page
862 # This is cleared one page view later in Article::viewUpdates();
867 * @access private
868 * @return string Encoding options
870 function encodeOptions() {
871 $a = array();
872 foreach ( $this->mOptions as $oname => $oval ) {
873 array_push( $a, $oname.'='.$oval );
875 $s = implode( "\n", $a );
876 return $s;
880 * @access private
882 function decodeOptions( $str ) {
883 $a = explode( "\n", $str );
884 foreach ( $a as $s ) {
885 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
886 $this->mOptions[$m[1]] = $m[2];
891 function setCookies() {
892 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
893 if ( 0 == $this->mId ) return;
894 $this->loadFromDatabase();
895 $exp = time() + $wgCookieExpiration;
897 $_SESSION['wsUserID'] = $this->mId;
898 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
900 $_SESSION['wsUserName'] = $this->mName;
901 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
903 $_SESSION['wsToken'] = $this->mToken;
904 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
905 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
906 } else {
907 setcookie( $wgDBname.'Token', '', time() - 3600 );
912 * Logout user
913 * It will clean the session cookie
915 function logout() {
916 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
917 $this->loadDefaults();
918 $this->setLoaded( true );
920 $_SESSION['wsUserID'] = 0;
922 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
923 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
925 # Remember when user logged out, to prevent seeing cached pages
926 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
930 * Save object settings into database
932 function saveSettings() {
933 global $wgMemc, $wgDBname;
934 $fname = 'User::saveSettings';
936 $dbw =& wfGetDB( DB_MASTER );
937 if ( ! $this->getNewtalk() ) {
938 # Delete the watchlist entry for user_talk page X watched by user X
939 $dbw->delete( 'watchlist',
940 array( 'wl_user' => $this->mId,
941 'wl_title' => $this->getTitleKey(),
942 'wl_namespace' => NS_USER_TALK ),
943 $fname );
944 if( !$this->mId ) {
945 # Anon users have a separate memcache space for newtalk
946 # since they don't store their own info. Trim...
947 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
951 if ( 0 == $this->mId ) { return; }
953 $dbw->update( 'user',
954 array( /* SET */
955 'user_name' => $this->mName,
956 'user_password' => $this->mPassword,
957 'user_newpassword' => $this->mNewpassword,
958 'user_real_name' => $this->mRealName,
959 'user_email' => $this->mEmail,
960 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp),
961 'user_options' => $this->encodeOptions(),
962 'user_touched' => $dbw->timestamp($this->mTouched),
963 'user_token' => $this->mToken
964 ), array( /* WHERE */
965 'user_id' => $this->mId
966 ), $fname
968 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
969 'ur_user='. $this->mId, $fname );
970 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
972 // delete old groups
973 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
975 // save new ones
976 foreach ($this->mGroups as $group) {
977 $dbw->replace( 'user_groups',
978 array(array('ug_user','ug_group')),
979 array(
980 'ug_user' => $this->mId,
981 'ug_group' => $group
982 ), $fname
989 * Checks if a user with the given name exists, returns the ID
991 function idForName() {
992 $fname = 'User::idForName';
994 $gotid = 0;
995 $s = trim( $this->mName );
996 if ( 0 == strcmp( '', $s ) ) return 0;
998 $dbr =& wfGetDB( DB_SLAVE );
999 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1000 if ( $id === false ) {
1001 $id = 0;
1003 return $id;
1007 * Add user object to the database
1009 function addToDatabase() {
1010 $fname = 'User::addToDatabase';
1011 $dbw =& wfGetDB( DB_MASTER );
1012 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1013 $dbw->insert( 'user',
1014 array(
1015 'user_id' => $seqVal,
1016 'user_name' => $this->mName,
1017 'user_password' => $this->mPassword,
1018 'user_newpassword' => $this->mNewpassword,
1019 'user_email' => $this->mEmail,
1020 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp),
1021 'user_real_name' => $this->mRealName,
1022 'user_options' => $this->encodeOptions(),
1023 'user_token' => $this->mToken
1024 ), $fname
1026 $this->mId = $dbw->insertId();
1027 $dbw->insert( 'user_rights',
1028 array(
1029 'ur_user' => $this->mId,
1030 'ur_rights' => implode( ',', $this->mRights )
1031 ), $fname
1034 foreach ($this->mGroups as $group) {
1035 $dbw->insert( 'user_groups',
1036 array(
1037 'ug_user' => $this->mId,
1038 'ug_group' => $group
1039 ), $fname
1044 function spreadBlock() {
1045 global $wgIP;
1046 # If the (non-anonymous) user is blocked, this function will block any IP address
1047 # that they successfully log on from.
1048 $fname = 'User::spreadBlock';
1050 wfDebug( "User:spreadBlock()\n" );
1051 if ( $this->mId == 0 ) {
1052 return;
1055 $userblock = Block::newFromDB( '', $this->mId );
1056 if ( !$userblock->isValid() ) {
1057 return;
1060 # Check if this IP address is already blocked
1061 $ipblock = Block::newFromDB( $wgIP );
1062 if ( $ipblock->isValid() ) {
1063 # Just update the timestamp
1064 $ipblock->updateTimestamp();
1065 return;
1068 # Make a new block object with the desired properties
1069 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1070 $ipblock->mAddress = $wgIP;
1071 $ipblock->mUser = 0;
1072 $ipblock->mBy = $userblock->mBy;
1073 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1074 $ipblock->mTimestamp = wfTimestampNow();
1075 $ipblock->mAuto = 1;
1076 # If the user is already blocked with an expiry date, we don't
1077 # want to pile on top of that!
1078 if($userblock->mExpiry) {
1079 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1080 } else {
1081 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1084 # Insert it
1085 $ipblock->insert();
1089 function getPageRenderingHash() {
1090 global $wgContLang;
1091 if( $this->mHash ){
1092 return $this->mHash;
1095 // stubthreshold is only included below for completeness,
1096 // it will always be 0 when this function is called by parsercache.
1098 $confstr = $this->getOption( 'math' );
1099 $confstr .= '!' . $this->getOption( 'highlightbroken' );
1100 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1101 $confstr .= '!' . $this->getOption( 'editsection' );
1102 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
1103 $confstr .= '!' . $this->getOption( 'showtoc' );
1104 $confstr .= '!' . $this->getOption( 'date' );
1105 $confstr .= '!' . $this->getOption( 'numberheadings' );
1106 $confstr .= '!' . $this->getOption( 'language' );
1107 // add in language specific options, if any
1108 $extra = $wgContLang->getExtraHashOptions();
1109 $confstr .= $extra;
1111 $this->mHash = $confstr;
1112 return $confstr ;
1115 function isAllowedToCreateAccount() {
1116 global $wgWhitelistAccount;
1117 $allowed = false;
1119 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1120 foreach ($wgWhitelistAccount as $right => $ok) {
1121 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1122 $allowed |= ($ok && $userHasRight);
1124 return $allowed;
1128 * Set mDataLoaded, return previous value
1129 * Use this to prevent DB access in command-line scripts or similar situations
1131 function setLoaded( $loaded ) {
1132 return wfSetVar( $this->mDataLoaded, $loaded );
1135 function getUserPage() {
1136 return Title::makeTitle( NS_USER, $this->mName );
1140 * @static
1142 function getMaxID() {
1143 $dbr =& wfGetDB( DB_SLAVE );
1144 return $dbr->selectField( 'user', 'max(user_id)', false );
1148 * Determine whether the user is a newbie. Newbies are either
1149 * anonymous IPs, or the 1% most recently created accounts.
1150 * Bots and sysops are excluded.
1151 * @return bool True if it is a newbie.
1153 function isNewbie() {
1154 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1158 * Check to see if the given clear-text password is one of the accepted passwords
1159 * @param string $password User password.
1160 * @return bool True if the given password is correct otherwise False.
1162 function checkPassword( $password ) {
1163 global $wgAuth;
1164 $this->loadFromDatabase();
1166 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1167 return true;
1168 } elseif( $wgAuth->strict() ) {
1169 /* Auth plugin doesn't allow local authentication */
1170 return false;
1172 $ep = $this->encryptPassword( $password );
1173 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1174 return true;
1175 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1176 $this->mEmailAuthenticationtimestamp = wfTimestampNow();
1177 $this->mNewpassword = ''; # use the temporary one-time password only once: clear it now !
1178 $this->saveSettings();
1179 return true;
1180 } elseif ( function_exists( 'iconv' ) ) {
1181 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1182 # Check for this with iconv
1183 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1184 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1185 return true;
1188 return false;
1192 * Initialize (if necessary) and return a session token value
1193 * which can be used in edit forms to show that the user's
1194 * login credentials aren't being hijacked with a foreign form
1195 * submission.
1197 * @return string
1198 * @access public
1200 function editToken() {
1201 if( !isset( $_SESSION['wsEditToken'] ) ) {
1202 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1203 $_SESSION['wsEditToken'] = $token;
1205 return $_SESSION['wsEditToken'];
1209 * Check given value against the token value stored in the session.
1210 * A match should confirm that the form was submitted from the
1211 * user's own login session, not a form submission from a third-party
1212 * site.
1214 * @param string $val
1215 * @return bool
1216 * @access public
1218 function matchEditToken( $val ) {
1219 if( !isset( $_SESSION['wsEditToken'] ) )
1220 return false;
1221 return $_SESSION['wsEditToken'] == $val;