* Avoid PHP warning messages when thumbnail not generated
[mediawiki.git] / includes / User.php
blobbecea050f9e9684f90304268302412de34fad6e0
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;
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->mTouched = '0'; # Allow any pages to be cached
179 $this->setToken(); # Random
180 $this->mHash = false;
181 wfProfileOut( $fname );
185 * Used to load user options from a language.
186 * This is not in loadDefault() cause we sometime create user before having
187 * a language object.
189 function loadDefaultFromLanguage(){
190 $this->mOptions = User::getDefaultOptions();
194 * Combine the language default options with any site-specific options
195 * and add the default language variants.
197 * @return array
198 * @static
199 * @access private
201 function getDefaultOptions() {
203 * Site defaults will override the global/language defaults
205 global $wgContLang, $wgDefaultUserOptions;
206 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
209 * default language setting
211 $variant = $wgContLang->getPreferredVariant();
212 $defOpt['variant'] = $variant;
213 $defOpt['language'] = $variant;
215 return $defOpt;
219 * Get a given default option value.
221 * @param string $opt
222 * @return string
223 * @static
224 * @access public
226 function getDefaultOption( $opt ) {
227 $defOpts = User::getDefaultOptions();
228 if( isset( $defOpts[$opt] ) ) {
229 return $defOpts[$opt];
230 } else {
231 return '';
236 * Get blocking information
237 * @access private
239 function getBlockedStatus() {
240 global $wgIP, $wgBlockCache, $wgProxyList;
242 if ( -1 != $this->mBlockedby ) { return; }
244 $this->mBlockedby = 0;
246 # User blocking
247 if ( $this->mId ) {
248 $block = new Block();
249 if ( $block->load( $wgIP , $this->mId ) ) {
250 $this->mBlockedby = $block->mBy;
251 $this->mBlockreason = $block->mReason;
255 # IP/range blocking
256 if ( !$this->mBlockedby ) {
257 $block = $wgBlockCache->get( $wgIP );
258 if ( $block !== false ) {
259 $this->mBlockedby = $block->mBy;
260 $this->mBlockreason = $block->mReason;
264 # Proxy blocking
265 if ( !$this->mBlockedby ) {
266 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
267 $this->mBlockreason = wfMsg( 'proxyblockreason' );
268 $this->mBlockedby = "Proxy blocker";
274 * Check if user is blocked
275 * @return bool True if blocked, false otherwise
277 function isBlocked() {
278 $this->getBlockedStatus();
279 if ( 0 === $this->mBlockedby ) { return false; }
280 return true;
284 * Get name of blocker
285 * @return string name of blocker
287 function blockedBy() {
288 $this->getBlockedStatus();
289 return $this->mBlockedby;
293 * Get blocking reason
294 * @return string Blocking reason
296 function blockedFor() {
297 $this->getBlockedStatus();
298 return $this->mBlockreason;
302 * Initialise php session
304 function SetupSession() {
305 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
306 if( $wgSessionsInMemcached ) {
307 require_once( 'MemcachedSessions.php' );
308 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
309 # If it's left on 'user' or another setting from another
310 # application, it will end up failing. Try to recover.
311 ini_set ( 'session.save_handler', 'files' );
313 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
314 session_cache_limiter( 'private, must-revalidate' );
315 @session_start();
319 * Read datas from session
320 * @static
322 function loadFromSession() {
323 global $wgMemc, $wgDBname;
325 if ( isset( $_SESSION['wsUserID'] ) ) {
326 if ( 0 != $_SESSION['wsUserID'] ) {
327 $sId = $_SESSION['wsUserID'];
328 } else {
329 return new User();
331 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
332 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
333 $_SESSION['wsUserID'] = $sId;
334 } else {
335 return new User();
337 if ( isset( $_SESSION['wsUserName'] ) ) {
338 $sName = $_SESSION['wsUserName'];
339 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
340 $sName = $_COOKIE["{$wgDBname}UserName"];
341 $_SESSION['wsUserName'] = $sName;
342 } else {
343 return new User();
346 $passwordCorrect = FALSE;
347 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
348 if($makenew = !$user) {
349 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
350 $user = new User();
351 $user->mId = $sId;
352 $user->loadFromDatabase();
353 } else {
354 wfDebug( "User::loadFromSession() got from cache!\n" );
357 if ( isset( $_SESSION['wsToken'] ) ) {
358 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
359 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
360 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
361 } else {
362 return new User(); # Can't log in from session
365 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
366 if($makenew) {
367 if($wgMemc->set( $key, $user ))
368 wfDebug( "User::loadFromSession() successfully saved user\n" );
369 else
370 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
372 $user->spreadBlock();
373 return $user;
375 return new User(); # Can't log in from session
379 * Load a user from the database
381 function loadFromDatabase() {
382 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
383 $fname = "User::loadFromDatabase";
384 if ( $this->mDataLoaded || $wgCommandLineMode ) {
385 return;
388 # Paranoia
389 $this->mId = IntVal( $this->mId );
391 /** Anonymous user */
392 if(!$this->mId) {
393 /** Get rights */
394 $anong = Group::newFromId($wgAnonGroupId);
395 if (!$anong)
396 wfDebugDieBacktrace("Please update your database schema "
397 ."and populate initial group data from "
398 ."maintenance/archives patches");
399 $anong->loadFromDatabase();
400 $this->mRights = explode(',', $anong->getRights());
401 $this->mDataLoaded = true;
402 return;
403 } # the following stuff is for non-anonymous users only
405 $dbr =& wfGetDB( DB_SLAVE );
406 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
407 'user_emailauthenticationtimestamp',
408 'user_real_name','user_options','user_touched', 'user_token' ),
409 array( 'user_id' => $this->mId ), $fname );
411 if ( $s !== false ) {
412 $this->mName = $s->user_name;
413 $this->mEmail = $s->user_email;
414 $this->mEmailAuthenticationtimestamp = $s->user_emailauthenticationtimestamp;
415 $this->mRealName = $s->user_real_name;
416 $this->mPassword = $s->user_password;
417 $this->mNewpassword = $s->user_newpassword;
418 $this->decodeOptions( $s->user_options );
419 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
420 $this->mToken = $s->user_token;
422 // Get groups id
423 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
425 while($group = $dbr->fetchRow($res)) {
426 $this->mGroups[] = $group[0];
429 // add the default group for logged in user
430 $this->mGroups[] = $wgLoggedInGroupId;
432 $this->mRights = array();
433 // now we merge groups rights to get this user rights
434 foreach($this->mGroups as $aGroupId) {
435 $g = Group::newFromId($aGroupId);
436 $g->loadFromDatabase();
437 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
440 // array merge duplicate rights which are part of several groups
441 $this->mRights = array_unique($this->mRights);
443 $dbr->freeResult($res);
446 $this->mDataLoaded = true;
449 function getID() { return $this->mId; }
450 function setID( $v ) {
451 $this->mId = $v;
452 $this->mDataLoaded = false;
455 function getName() {
456 $this->loadFromDatabase();
457 return $this->mName;
460 function setName( $str ) {
461 $this->loadFromDatabase();
462 $this->mName = $str;
467 * Return the title dbkey form of the name, for eg user pages.
468 * @return string
469 * @access public
471 function getTitleKey() {
472 return str_replace( ' ', '_', $this->getName() );
475 function getNewtalk() {
476 $fname = 'User::getNewtalk';
477 $this->loadFromDatabase();
479 # Load the newtalk status if it is unloaded (mNewtalk=-1)
480 if( $this->mNewtalk == -1 ) {
481 $this->mNewtalk = 0; # reset talk page status
483 # Check memcached separately for anons, who have no
484 # entire User object stored in there.
485 if( !$this->mId ) {
486 global $wgDBname, $wgMemc;
487 $key = "$wgDBname:newtalk:ip:{$this->mName}";
488 $newtalk = $wgMemc->get( $key );
489 if( is_integer( $newtalk ) ) {
490 $this->mNewtalk = $newtalk ? 1 : 0;
491 return (bool)$this->mNewtalk;
495 $dbr =& wfGetDB( DB_SLAVE );
496 $res = $dbr->select( 'watchlist',
497 array( 'wl_user' ),
498 array( 'wl_title' => $this->getTitleKey(),
499 'wl_namespace' => NS_USER_TALK,
500 'wl_user' => $this->mId,
501 'wl_notificationtimestamp != 0' ),
502 'User::getNewtalk' );
503 if( $dbr->numRows($res) > 0 ) {
504 $this->mNewtalk = 1;
506 $dbr->freeResult( $res );
508 if( !$this->mId ) {
509 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
513 return ( 0 != $this->mNewtalk );
516 function setNewtalk( $val ) {
517 $this->loadFromDatabase();
518 $this->mNewtalk = $val;
519 $this->invalidateCache();
522 function invalidateCache() {
523 $this->loadFromDatabase();
524 $this->mTouched = wfTimestampNow();
525 # Don't forget to save the options after this or
526 # it won't take effect!
529 function validateCache( $timestamp ) {
530 $this->loadFromDatabase();
531 return ($timestamp >= $this->mTouched);
535 * Salt a password.
536 * Will only be salted if $wgPasswordSalt is true
537 * @param string Password.
538 * @return string Salted password or clear password.
540 function addSalt( $p ) {
541 global $wgPasswordSalt;
542 if($wgPasswordSalt)
543 return md5( "{$this->mId}-{$p}" );
544 else
545 return $p;
549 * Encrypt a password.
550 * It can eventuall salt a password @see User::addSalt()
551 * @param string $p clear Password.
552 * @param string Encrypted password.
554 function encryptPassword( $p ) {
555 return $this->addSalt( md5( $p ) );
558 # Set the password and reset the random token
559 function setPassword( $str ) {
560 $this->loadFromDatabase();
561 $this->setToken();
562 $this->mPassword = $this->encryptPassword( $str );
563 $this->mNewpassword = '';
566 # Set the random token (used for persistent authentication)
567 function setToken( $token = false ) {
568 if ( !$token ) {
569 $this->mToken = '';
570 # Take random data from PRNG
571 # This is reasonably secure if the PRNG has been seeded correctly
572 for ($i = 0; $i<USER_TOKEN_LENGTH / 4; $i++) {
573 $this->mToken .= sprintf( "%04X", mt_rand( 0, 65535 ) );
575 } else {
576 $this->mToken = $token;
581 function setCookiePassword( $str ) {
582 $this->loadFromDatabase();
583 $this->mCookiePassword = md5( $str );
586 function setNewpassword( $str ) {
587 $this->loadFromDatabase();
588 $this->mNewpassword = $this->encryptPassword( $str );
591 function getEmail() {
592 $this->loadFromDatabase();
593 return $this->mEmail;
596 function getEmailAuthenticationtimestamp() {
597 $this->loadFromDatabase();
598 return $this->mEmailAuthenticationtimestamp;
601 function setEmail( $str ) {
602 $this->loadFromDatabase();
603 $this->mEmail = $str;
606 function getRealName() {
607 $this->loadFromDatabase();
608 return $this->mRealName;
611 function setRealName( $str ) {
612 $this->loadFromDatabase();
613 $this->mRealName = $str;
616 function getOption( $oname ) {
617 $this->loadFromDatabase();
618 if ( array_key_exists( $oname, $this->mOptions ) ) {
619 return $this->mOptions[$oname];
620 } else {
621 return '';
625 function setOption( $oname, $val ) {
626 $this->loadFromDatabase();
627 if ( $oname == 'skin' ) {
628 # Clear cached skin, so the new one displays immediately in Special:Preferences
629 unset( $this->mSkin );
631 $this->mOptions[$oname] = $val;
632 $this->invalidateCache();
635 function getRights() {
636 $this->loadFromDatabase();
637 return $this->mRights;
640 function addRight( $rname ) {
641 $this->loadFromDatabase();
642 array_push( $this->mRights, $rname );
643 $this->invalidateCache();
646 function getGroups() {
647 $this->loadFromDatabase();
648 return $this->mGroups;
651 function setGroups($groups) {
652 $this->loadFromDatabase();
653 $this->mGroups = $groups;
654 $this->invalidateCache();
658 * Check if a user is sysop
659 * Die with backtrace. Use User:isAllowed() instead.
660 * @deprecated
662 function isSysop() {
664 $this->loadFromDatabase();
665 if ( 0 == $this->mId ) { return false; }
667 return in_array( 'sysop', $this->mRights );
669 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
672 /** @deprecated */
673 function isDeveloper() {
675 $this->loadFromDatabase();
676 if ( 0 == $this->mId ) { return false; }
678 return in_array( 'developer', $this->mRights );
680 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
683 /** @deprecated */
684 function isBureaucrat() {
686 $this->loadFromDatabase();
687 if ( 0 == $this->mId ) { return false; }
689 return in_array( 'bureaucrat', $this->mRights );
691 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
695 * Whether the user is a bot
696 * @todo need to be migrated to the new user level management sytem
698 function isBot() {
699 $this->loadFromDatabase();
701 # Why was this here? I need a UID=0 conversion script [TS]
702 # if ( 0 == $this->mId ) { return false; }
704 return in_array( 'bot', $this->mRights );
708 * Check if user is allowed to access a feature / make an action
709 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
710 * @return boolean True: action is allowed, False: action should not be allowed
712 function isAllowed($action='') {
713 $this->loadFromDatabase();
714 return in_array( $action , $this->mRights );
718 * Load a skin if it doesn't exist or return it
719 * @todo FIXME : need to check the old failback system [AV]
721 function &getSkin() {
722 global $IP;
723 if ( ! isset( $this->mSkin ) ) {
724 $fname = 'User::getSkin';
725 wfProfileIn( $fname );
727 # get all skin names available
728 $skinNames = Skin::getSkinNames();
730 # get the user skin
731 $userSkin = $this->getOption( 'skin' );
732 if ( $userSkin == '' ) { $userSkin = 'standard'; }
734 if ( !isset( $skinNames[$userSkin] ) ) {
735 # in case the user skin could not be found find a replacement
736 $fallback = array(
737 0 => 'Standard',
738 1 => 'Nostalgia',
739 2 => 'CologneBlue');
740 # if phptal is enabled we should have monobook skin that
741 # superseed the good old SkinStandard.
742 if ( isset( $skinNames['monobook'] ) ) {
743 $fallback[0] = 'MonoBook';
746 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
747 $sn = $fallback[$userSkin];
748 } else {
749 $sn = 'Standard';
751 } else {
752 # The user skin is available
753 $sn = $skinNames[$userSkin];
756 # Grab the skin class and initialise it. Each skin checks for PHPTal
757 # and will not load if it's not enabled.
758 require_once( $IP.'/skins/'.$sn.'.php' );
760 # Check if we got if not failback to default skin
761 $className = 'Skin'.$sn;
762 if( !class_exists( $className ) ) {
763 # DO NOT die if the class isn't found. This breaks maintenance
764 # scripts and can cause a user account to be unrecoverable
765 # except by SQL manipulation if a previously valid skin name
766 # is no longer valid.
767 $className = 'SkinStandard';
768 require_once( $IP.'/skins/Standard.php' );
770 $this->mSkin =& new $className;
771 wfProfileOut( $fname );
773 return $this->mSkin;
776 /**#@+
777 * @param string $title Article title to look at
781 * Check watched status of an article
782 * @return bool True if article is watched
784 function isWatched( $title ) {
785 $wl = WatchedItem::fromUserTitle( $this, $title );
786 return $wl->isWatched();
790 * Watch an article
792 function addWatch( $title ) {
793 $wl = WatchedItem::fromUserTitle( $this, $title );
794 $wl->addWatch();
795 $this->invalidateCache();
799 * Stop watching an article
801 function removeWatch( $title ) {
802 $wl = WatchedItem::fromUserTitle( $this, $title );
803 $wl->removeWatch();
804 $this->invalidateCache();
808 * Clear the user's notification timestamp for the given title.
809 * If e-notif e-mails are on, they will receive notification mails on
810 * the next change of the page if it's watched etc.
812 function clearNotification( $title ) {
813 $dbw =& wfGetDB( DB_MASTER );
814 $success = $dbw->update( 'watchlist',
815 array( /* SET */
816 'wl_notificationtimestamp' => 0
817 ), array( /* WHERE */
818 'wl_title' => $title->getDBkey(),
819 'wl_namespace' => $title->getNamespace(),
820 'wl_user' => $this->getId()
821 ), 'User::clearLastVisited'
825 /**#@-*/
828 * Resets all of the given user's page-change notification timestamps.
829 * If e-notif e-mails are on, they will receive notification mails on
830 * the next change of any watched page.
832 * @param int $currentUser user ID number
833 * @access public
835 function clearAllNotifications( $currentUser ) {
836 if( $currentUser != 0 ) {
838 $dbw =& wfGetDB( DB_MASTER );
839 $success = $dbw->update( 'watchlist',
840 array( /* SET */
841 'wl_notificationtimestamp' => 0
842 ), array( /* WHERE */
843 'wl_user' => $currentUser
844 ), 'UserMailer::clearAll'
847 # we also need to clear here the "you have new message" notification for the own user_talk page
848 # This is cleared one page view later in Article::viewUpdates();
853 * @access private
854 * @return string Encoding options
856 function encodeOptions() {
857 $a = array();
858 foreach ( $this->mOptions as $oname => $oval ) {
859 array_push( $a, $oname.'='.$oval );
861 $s = implode( "\n", $a );
862 return $s;
866 * @access private
868 function decodeOptions( $str ) {
869 $a = explode( "\n", $str );
870 foreach ( $a as $s ) {
871 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
872 $this->mOptions[$m[1]] = $m[2];
877 function setCookies() {
878 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
879 if ( 0 == $this->mId ) return;
880 $this->loadFromDatabase();
881 $exp = time() + $wgCookieExpiration;
883 $_SESSION['wsUserID'] = $this->mId;
884 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
886 $_SESSION['wsUserName'] = $this->mName;
887 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
889 $_SESSION['wsToken'] = $this->mToken;
890 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
891 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
892 } else {
893 setcookie( $wgDBname.'Token', '', time() - 3600 );
898 * Logout user
899 * It will clean the session cookie
901 function logout() {
902 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
903 $this->loadDefaults();
904 $this->setLoaded( true );
906 $_SESSION['wsUserID'] = 0;
908 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
909 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
913 * Save object settings into database
915 function saveSettings() {
916 global $wgMemc, $wgDBname;
917 $fname = 'User::saveSettings';
919 $dbw =& wfGetDB( DB_MASTER );
920 if ( ! $this->getNewtalk() ) {
921 # Delete the watchlist entry for user_talk page X watched by user X
922 $dbw->delete( 'watchlist',
923 array( 'wl_user' => $this->mId,
924 'wl_title' => $this->getTitleKey(),
925 'wl_namespace' => NS_USER_TALK ),
926 $fname );
927 if( !$this->mId ) {
928 # Anon users have a separate memcache space for newtalk
929 # since they don't store their own info. Trim...
930 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
934 if ( 0 == $this->mId ) { return; }
936 $dbw->update( 'user',
937 array( /* SET */
938 'user_name' => $this->mName,
939 'user_password' => $this->mPassword,
940 'user_newpassword' => $this->mNewpassword,
941 'user_real_name' => $this->mRealName,
942 'user_email' => $this->mEmail,
943 'user_emailauthenticationtimestamp' => $this->mEmailAuthenticationtimestamp,
944 'user_options' => $this->encodeOptions(),
945 'user_touched' => $dbw->timestamp($this->mTouched),
946 'user_token' => $this->mToken
947 ), array( /* WHERE */
948 'user_id' => $this->mId
949 ), $fname
951 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
952 'ur_user='. $this->mId, $fname );
953 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
955 // delete old groups
956 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
958 // save new ones
959 foreach ($this->mGroups as $group) {
960 $dbw->replace( 'user_groups',
961 array(array('ug_user','ug_group')),
962 array(
963 'ug_user' => $this->mId,
964 'ug_group' => $group
965 ), $fname
972 * Checks if a user with the given name exists, returns the ID
974 function idForName() {
975 $fname = 'User::idForName';
977 $gotid = 0;
978 $s = trim( $this->mName );
979 if ( 0 == strcmp( '', $s ) ) return 0;
981 $dbr =& wfGetDB( DB_SLAVE );
982 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
983 if ( $id === false ) {
984 $id = 0;
986 return $id;
990 * Add user object to the database
992 function addToDatabase() {
993 $fname = 'User::addToDatabase';
994 $dbw =& wfGetDB( DB_MASTER );
995 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
996 $dbw->insert( 'user',
997 array(
998 'user_id' => $seqVal,
999 'user_name' => $this->mName,
1000 'user_password' => $this->mPassword,
1001 'user_newpassword' => $this->mNewpassword,
1002 'user_email' => $this->mEmail,
1003 'user_emailauthenticationtimestamp' => $this->mEmailAuthenticationtimestamp,
1004 'user_real_name' => $this->mRealName,
1005 'user_options' => $this->encodeOptions(),
1006 'user_token' => $this->mToken
1007 ), $fname
1009 $this->mId = $dbw->insertId();
1010 $dbw->insert( 'user_rights',
1011 array(
1012 'ur_user' => $this->mId,
1013 'ur_rights' => implode( ',', $this->mRights )
1014 ), $fname
1017 foreach ($this->mGroups as $group) {
1018 $dbw->insert( 'user_groups',
1019 array(
1020 'ug_user' => $this->mId,
1021 'ug_group' => $group
1022 ), $fname
1027 function spreadBlock() {
1028 global $wgIP;
1029 # If the (non-anonymous) user is blocked, this function will block any IP address
1030 # that they successfully log on from.
1031 $fname = 'User::spreadBlock';
1033 wfDebug( "User:spreadBlock()\n" );
1034 if ( $this->mId == 0 ) {
1035 return;
1038 $userblock = Block::newFromDB( '', $this->mId );
1039 if ( !$userblock->isValid() ) {
1040 return;
1043 # Check if this IP address is already blocked
1044 $ipblock = Block::newFromDB( $wgIP );
1045 if ( $ipblock->isValid() ) {
1046 # Just update the timestamp
1047 $ipblock->updateTimestamp();
1048 return;
1051 # Make a new block object with the desired properties
1052 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1053 $ipblock->mAddress = $wgIP;
1054 $ipblock->mUser = 0;
1055 $ipblock->mBy = $userblock->mBy;
1056 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1057 $ipblock->mTimestamp = wfTimestampNow();
1058 $ipblock->mAuto = 1;
1059 # If the user is already blocked with an expiry date, we don't
1060 # want to pile on top of that!
1061 if($userblock->mExpiry) {
1062 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1063 } else {
1064 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1067 # Insert it
1068 $ipblock->insert();
1072 function getPageRenderingHash() {
1073 global $wgContLang;
1074 if( $this->mHash ){
1075 return $this->mHash;
1078 // stubthreshold is only included below for completeness,
1079 // it will always be 0 when this function is called by parsercache.
1081 $confstr = $this->getOption( 'math' );
1082 $confstr .= '!' . $this->getOption( 'highlightbroken' );
1083 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1084 $confstr .= '!' . $this->getOption( 'editsection' );
1085 $confstr .= '!' . $this->getOption( 'editsectiononrightclick' );
1086 $confstr .= '!' . $this->getOption( 'showtoc' );
1087 $confstr .= '!' . $this->getOption( 'date' );
1088 $confstr .= '!' . $this->getOption( 'numberheadings' );
1089 $confstr .= '!' . $this->getOption( 'language' );
1090 // add in language specific options, if any
1091 $extra = $wgContLang->getExtraHashOptions();
1092 foreach( $extra as $e ) {
1093 $confstr .= '!' . $this->getOption( $e );
1096 $this->mHash = $confstr;
1097 return $confstr ;
1100 function isAllowedToCreateAccount() {
1101 global $wgWhitelistAccount;
1102 $allowed = false;
1104 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1105 foreach ($wgWhitelistAccount as $right => $ok) {
1106 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1107 $allowed |= ($ok && $userHasRight);
1109 return $allowed;
1113 * Set mDataLoaded, return previous value
1114 * Use this to prevent DB access in command-line scripts or similar situations
1116 function setLoaded( $loaded ) {
1117 return wfSetVar( $this->mDataLoaded, $loaded );
1120 function getUserPage() {
1121 return Title::makeTitle( NS_USER, $this->mName );
1125 * @static
1127 function getMaxID() {
1128 $dbr =& wfGetDB( DB_SLAVE );
1129 return $dbr->selectField( 'user', 'max(user_id)', false );
1133 * Determine whether the user is a newbie. Newbies are either
1134 * anonymous IPs, or the 1% most recently created accounts.
1135 * Bots and sysops are excluded.
1136 * @return bool True if it is a newbie.
1138 function isNewbie() {
1139 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1143 * Check to see if the given clear-text password is one of the accepted passwords
1144 * @param string $password User password.
1145 * @return bool True if the given password is correct otherwise False.
1147 function checkPassword( $password ) {
1148 global $wgAuth;
1149 $this->loadFromDatabase();
1151 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1152 return true;
1153 } elseif( $wgAuth->strict() ) {
1154 /* Auth plugin doesn't allow local authentication */
1155 return false;
1157 $ep = $this->encryptPassword( $password );
1158 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1159 return true;
1160 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1161 $this->mEmailAuthenticationtimestamp = wfTimestampNow();
1162 $this->mNewpassword = ''; # use the temporary one-time password only once: clear it now !
1163 $this->saveSettings();
1164 return true;
1165 } elseif ( function_exists( 'iconv' ) ) {
1166 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1167 # Check for this with iconv
1168 /* $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1169 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1170 return true;
1173 return false;