new function: getBrokenLinksFrom()
[mediawiki.git] / includes / User.php
blobae3d43df3762fecf5ef77d5aefbe2624c3808d40
1 <?php
2 /**
3 * See user.txt
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 ?
122 * @bug 959
124 * @param string $addr email address
125 * @static
126 * @return bool
128 function isValidEmailAddr ( $addr ) {
129 # There used to be a regular expression here, it got removed because it
130 # rejected valid addresses.
131 return true;
135 * probably return a random password
136 * @return string probably a random password
137 * @static
138 * @todo Check what is doing really [AV]
140 function randomPassword() {
141 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
142 $l = strlen( $pwchars ) - 1;
144 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
145 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
146 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
147 $pwchars{mt_rand( 0, $l )};
148 return $np;
152 * Set properties to default
153 * Used at construction. It will load per language default settings only
154 * if we have an available language object.
156 function loadDefaults() {
157 static $n=0;
158 $n++;
159 $fname = 'User::loadDefaults' . $n;
160 wfProfileIn( $fname );
162 global $wgContLang, $wgIP, $wgDBname;
163 global $wgNamespacesToBeSearchedDefault;
165 $this->mId = 0;
166 $this->mNewtalk = -1;
167 $this->mName = $wgIP;
168 $this->mRealName = $this->mEmail = '';
169 $this->mEmailAuthenticationtimestamp = 0;
170 $this->mPassword = $this->mNewpassword = '';
171 $this->mRights = array();
172 $this->mGroups = array();
173 // Getting user defaults only if we have an available language
174 if( isset( $wgContLang ) ) {
175 $this->loadDefaultFromLanguage();
178 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
179 $this->mOptions['searchNs'.$nsnum] = $val;
181 unset( $this->mSkin );
182 $this->mDataLoaded = false;
183 $this->mBlockedby = -1; # Unset
184 $this->setToken(); # Random
185 $this->mHash = false;
187 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
188 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
190 else {
191 $this->mTouched = '0'; # Allow any pages to be cached
194 wfProfileOut( $fname );
198 * Used to load user options from a language.
199 * This is not in loadDefault() cause we sometime create user before having
200 * a language object.
202 function loadDefaultFromLanguage(){
203 $this->mOptions = User::getDefaultOptions();
207 * Combine the language default options with any site-specific options
208 * and add the default language variants.
210 * @return array
211 * @static
212 * @access private
214 function getDefaultOptions() {
216 * Site defaults will override the global/language defaults
218 global $wgContLang, $wgDefaultUserOptions;
219 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
222 * default language setting
224 $variant = $wgContLang->getPreferredVariant();
225 $defOpt['variant'] = $variant;
226 $defOpt['language'] = $variant;
228 return $defOpt;
232 * Get a given default option value.
234 * @param string $opt
235 * @return string
236 * @static
237 * @access public
239 function getDefaultOption( $opt ) {
240 $defOpts = User::getDefaultOptions();
241 if( isset( $defOpts[$opt] ) ) {
242 return $defOpts[$opt];
243 } else {
244 return '';
249 * Get blocking information
250 * @access private
251 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
252 * non-critical checks are done against slaves. Check when actually saving should be done against
253 * master.
255 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
256 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
257 * just slightly outta sync and soon corrected - safer to block slightly more that less.
258 * And it's cheaper to check slave first, then master if needed, than master always.
260 function getBlockedStatus() {
261 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $bFromSlave;
263 if ( -1 != $this->mBlockedby ) { return; }
265 $this->mBlockedby = 0;
267 # User blocking
268 if ( $this->mId ) {
269 $block = new Block();
270 $block->forUpdate( $bFromSlave );
271 if ( $block->load( $wgIP , $this->mId ) ) {
272 $this->mBlockedby = $block->mBy;
273 $this->mBlockreason = $block->mReason;
274 $this->spreadBlock();
278 # IP/range blocking
279 if ( !$this->mBlockedby ) {
280 # Check first against slave, and optionally from master.
281 $block = $wgBlockCache->get( $wgIP, true );
282 if ( !$block && !$bFromSlave )
284 # Not blocked: check against master, to make sure.
285 $wgBlockCache->clearLocal( );
286 $block = $wgBlockCache->get( $wgIP, false );
288 if ( $block !== false ) {
289 $this->mBlockedby = $block->mBy;
290 $this->mBlockreason = $block->mReason;
294 # Proxy blocking
295 if ( !$this->mBlockedby ) {
296 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
297 $this->mBlockedby = wfMsg( 'proxyblocker' );
298 $this->mBlockreason = wfMsg( 'proxyblockreason' );
302 # DNSBL
303 if ( !$this->mBlockedby && $wgEnableSorbs ) {
304 if ( $this->inSorbsBlacklist( $wgIP ) ) {
305 $this->mBlockedby = wfMsg( 'sorbs' );
306 $this->mBlockreason = wfMsg( 'sorbsreason' );
312 function inSorbsBlacklist( $ip ) {
313 $fname = 'User::inSorbsBlacklist';
314 wfProfileIn( $fname );
316 $found = false;
317 $host = '';
319 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
320 # Make hostname
321 for ( $i=4; $i>=1; $i-- ) {
322 $host .= $m[$i] . '.';
324 $host .= 'http.dnsbl.sorbs.net.';
326 # Send query
327 $ipList = gethostbynamel( $host );
329 if ( $ipList ) {
330 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy!\n" );
331 $found = true;
332 } else {
333 wfDebug( "Requested $host, not found.\n" );
337 wfProfileOut( $fname );
338 return $found;
342 * Check if user is blocked
343 * @return bool True if blocked, false otherwise
345 function isBlocked( $bFromSlave = false ) {
346 $this->getBlockedStatus( $bFromSlave );
347 if ( 0 === $this->mBlockedby ) { return false; }
348 return true;
352 * Get name of blocker
353 * @return string name of blocker
355 function blockedBy() {
356 $this->getBlockedStatus();
357 return $this->mBlockedby;
361 * Get blocking reason
362 * @return string Blocking reason
364 function blockedFor() {
365 $this->getBlockedStatus();
366 return $this->mBlockreason;
370 * Initialise php session
372 function SetupSession() {
373 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
374 if( $wgSessionsInMemcached ) {
375 require_once( 'MemcachedSessions.php' );
376 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
377 # If it's left on 'user' or another setting from another
378 # application, it will end up failing. Try to recover.
379 ini_set ( 'session.save_handler', 'files' );
381 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
382 session_cache_limiter( 'private, must-revalidate' );
383 @session_start();
387 * Read datas from session
388 * @static
390 function loadFromSession() {
391 global $wgMemc, $wgDBname;
393 if ( isset( $_SESSION['wsUserID'] ) ) {
394 if ( 0 != $_SESSION['wsUserID'] ) {
395 $sId = $_SESSION['wsUserID'];
396 } else {
397 return new User();
399 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
400 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
401 $_SESSION['wsUserID'] = $sId;
402 } else {
403 return new User();
405 if ( isset( $_SESSION['wsUserName'] ) ) {
406 $sName = $_SESSION['wsUserName'];
407 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
408 $sName = $_COOKIE["{$wgDBname}UserName"];
409 $_SESSION['wsUserName'] = $sName;
410 } else {
411 return new User();
414 $passwordCorrect = FALSE;
415 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
416 if($makenew = !$user) {
417 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
418 $user = new User();
419 $user->mId = $sId;
420 $user->loadFromDatabase();
421 } else {
422 wfDebug( "User::loadFromSession() got from cache!\n" );
425 if ( isset( $_SESSION['wsToken'] ) ) {
426 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
427 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
428 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
429 } else {
430 return new User(); # Can't log in from session
433 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
434 if($makenew) {
435 if($wgMemc->set( $key, $user ))
436 wfDebug( "User::loadFromSession() successfully saved user\n" );
437 else
438 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
440 return $user;
442 return new User(); # Can't log in from session
446 * Load a user from the database
448 function loadFromDatabase() {
449 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
450 $fname = "User::loadFromDatabase";
452 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
453 # loading in a command line script, don't assume all command line scripts need it like this
454 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
455 if ( $this->mDataLoaded ) {
456 return;
459 # Paranoia
460 $this->mId = IntVal( $this->mId );
462 /** Anonymous user */
463 if(!$this->mId) {
464 /** Get rights */
465 $anong = Group::newFromId($wgAnonGroupId);
466 if (!$anong)
467 wfDebugDieBacktrace("Please update your database schema "
468 ."and populate initial group data from "
469 ."maintenance/archives patches");
470 $anong->loadFromDatabase();
471 $this->mRights = explode(',', $anong->getRights());
472 $this->mDataLoaded = true;
473 return;
474 } # the following stuff is for non-anonymous users only
476 $dbr =& wfGetDB( DB_SLAVE );
477 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
478 'user_emailauthenticationtimestamp',
479 'user_real_name','user_options','user_touched', 'user_token' ),
480 array( 'user_id' => $this->mId ), $fname );
482 if ( $s !== false ) {
483 $this->mName = $s->user_name;
484 $this->mEmail = $s->user_email;
485 $this->mEmailAuthenticationtimestamp = wfTimestamp(TS_MW,$s->user_emailauthenticationtimestamp);
486 $this->mRealName = $s->user_real_name;
487 $this->mPassword = $s->user_password;
488 $this->mNewpassword = $s->user_newpassword;
489 $this->decodeOptions( $s->user_options );
490 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
491 $this->mToken = $s->user_token;
493 // Get groups id
494 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ) );
496 while($group = $dbr->fetchRow($res)) {
497 $this->mGroups[] = $group[0];
500 // add the default group for logged in user
501 $this->mGroups[] = $wgLoggedInGroupId;
503 $this->mRights = array();
504 // now we merge groups rights to get this user rights
505 foreach($this->mGroups as $aGroupId) {
506 $g = Group::newFromId($aGroupId);
507 $g->loadFromDatabase();
508 $this->mRights = array_merge($this->mRights, explode(',', $g->getRights()));
511 // array merge duplicate rights which are part of several groups
512 $this->mRights = array_unique($this->mRights);
514 $dbr->freeResult($res);
517 $this->mDataLoaded = true;
520 function getID() { return $this->mId; }
521 function setID( $v ) {
522 $this->mId = $v;
523 $this->mDataLoaded = false;
526 function getName() {
527 $this->loadFromDatabase();
528 return $this->mName;
531 function setName( $str ) {
532 $this->loadFromDatabase();
533 $this->mName = $str;
538 * Return the title dbkey form of the name, for eg user pages.
539 * @return string
540 * @access public
542 function getTitleKey() {
543 return str_replace( ' ', '_', $this->getName() );
546 function getNewtalk() {
547 $fname = 'User::getNewtalk';
548 $this->loadFromDatabase();
550 # Load the newtalk status if it is unloaded (mNewtalk=-1)
551 if( $this->mNewtalk == -1 ) {
552 $this->mNewtalk = 0; # reset talk page status
554 # Check memcached separately for anons, who have no
555 # entire User object stored in there.
556 if( !$this->mId ) {
557 global $wgDBname, $wgMemc;
558 $key = "$wgDBname:newtalk:ip:{$this->mName}";
559 $newtalk = $wgMemc->get( $key );
560 if( is_integer( $newtalk ) ) {
561 $this->mNewtalk = $newtalk ? 1 : 0;
562 return (bool)$this->mNewtalk;
566 $dbr =& wfGetDB( DB_SLAVE );
567 $res = $dbr->select( 'watchlist',
568 array( 'wl_user' ),
569 array( 'wl_title' => $this->getTitleKey(),
570 'wl_namespace' => NS_USER_TALK,
571 'wl_user' => $this->mId,
572 'wl_notificationtimestamp != 0' ),
573 'User::getNewtalk' );
574 if( $dbr->numRows($res) > 0 ) {
575 $this->mNewtalk = 1;
577 $dbr->freeResult( $res );
579 if( !$this->mId ) {
580 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
584 return ( 0 != $this->mNewtalk );
587 function setNewtalk( $val ) {
588 $this->loadFromDatabase();
589 $this->mNewtalk = $val;
590 $this->invalidateCache();
593 function invalidateCache() {
594 $this->loadFromDatabase();
595 $this->mTouched = wfTimestampNow();
596 # Don't forget to save the options after this or
597 # it won't take effect!
600 function validateCache( $timestamp ) {
601 $this->loadFromDatabase();
602 return ($timestamp >= $this->mTouched);
606 * Salt a password.
607 * Will only be salted if $wgPasswordSalt is true
608 * @param string Password.
609 * @return string Salted password or clear password.
611 function addSalt( $p ) {
612 global $wgPasswordSalt;
613 if($wgPasswordSalt)
614 return md5( "{$this->mId}-{$p}" );
615 else
616 return $p;
620 * Encrypt a password.
621 * It can eventuall salt a password @see User::addSalt()
622 * @param string $p clear Password.
623 * @param string Encrypted password.
625 function encryptPassword( $p ) {
626 return $this->addSalt( md5( $p ) );
629 # Set the password and reset the random token
630 function setPassword( $str ) {
631 $this->loadFromDatabase();
632 $this->setToken();
633 $this->mPassword = $this->encryptPassword( $str );
634 $this->mNewpassword = '';
637 # Set the random token (used for persistent authentication)
638 function setToken( $token = false ) {
639 global $wgSecretKey, $wgProxyKey, $wgDBname;
640 if ( !$token ) {
641 if ( $wgSecretKey ) {
642 $key = $wgSecretKey;
643 } elseif ( $wgProxyKey ) {
644 $key = $wgProxyKey;
645 } else {
646 $key = microtime();
648 $this->mToken = md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
649 } else {
650 $this->mToken = $token;
655 function setCookiePassword( $str ) {
656 $this->loadFromDatabase();
657 $this->mCookiePassword = md5( $str );
660 function setNewpassword( $str ) {
661 $this->loadFromDatabase();
662 $this->mNewpassword = $this->encryptPassword( $str );
665 function getEmail() {
666 $this->loadFromDatabase();
667 return $this->mEmail;
670 function getEmailAuthenticationtimestamp() {
671 $this->loadFromDatabase();
672 return $this->mEmailAuthenticationtimestamp;
675 function setEmail( $str ) {
676 $this->loadFromDatabase();
677 $this->mEmail = $str;
680 function getRealName() {
681 $this->loadFromDatabase();
682 return $this->mRealName;
685 function setRealName( $str ) {
686 $this->loadFromDatabase();
687 $this->mRealName = $str;
690 function getOption( $oname ) {
691 $this->loadFromDatabase();
692 if ( array_key_exists( $oname, $this->mOptions ) ) {
693 return $this->mOptions[$oname];
694 } else {
695 return '';
699 function setOption( $oname, $val ) {
700 $this->loadFromDatabase();
701 if ( $oname == 'skin' ) {
702 # Clear cached skin, so the new one displays immediately in Special:Preferences
703 unset( $this->mSkin );
705 $this->mOptions[$oname] = $val;
706 $this->invalidateCache();
709 function getRights() {
710 $this->loadFromDatabase();
711 return $this->mRights;
714 function addRight( $rname ) {
715 $this->loadFromDatabase();
716 array_push( $this->mRights, $rname );
717 $this->invalidateCache();
720 function getGroups() {
721 $this->loadFromDatabase();
722 return $this->mGroups;
725 function setGroups($groups) {
726 $this->loadFromDatabase();
727 $this->mGroups = $groups;
728 $this->invalidateCache();
732 * A more legible check for non-anonymousness.
733 * Returns true if the user is not an anonymous visitor.
735 * @return bool
737 function isLoggedIn() {
738 return( $this->getID() != 0 );
742 * A more legible check for anonymousness.
743 * Returns true if the user is an anonymous visitor.
745 * @return bool
747 function isAnon() {
748 return !$this->isLoggedIn();
752 * Check if a user is sysop
753 * Die with backtrace. Use User:isAllowed() instead.
754 * @deprecated
756 function isSysop() {
757 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
760 /** @deprecated */
761 function isDeveloper() {
762 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
765 /** @deprecated */
766 function isBureaucrat() {
767 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
771 * Whether the user is a bot
772 * @todo need to be migrated to the new user level management sytem
774 function isBot() {
775 $this->loadFromDatabase();
777 # Why was this here? I need a UID=0 conversion script [TS]
778 # if ( 0 == $this->mId ) { return false; }
780 return in_array( 'bot', $this->mRights );
784 * Check if user is allowed to access a feature / make an action
785 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
786 * @return boolean True: action is allowed, False: action should not be allowed
788 function isAllowed($action='') {
789 $this->loadFromDatabase();
790 return in_array( $action , $this->mRights );
794 * Load a skin if it doesn't exist or return it
795 * @todo FIXME : need to check the old failback system [AV]
797 function &getSkin() {
798 global $IP;
799 if ( ! isset( $this->mSkin ) ) {
800 $fname = 'User::getSkin';
801 wfProfileIn( $fname );
803 # get all skin names available
804 $skinNames = Skin::getSkinNames();
806 # get the user skin
807 $userSkin = $this->getOption( 'skin' );
808 if ( $userSkin == '' ) { $userSkin = 'standard'; }
810 if ( !isset( $skinNames[$userSkin] ) ) {
811 # in case the user skin could not be found find a replacement
812 $fallback = array(
813 0 => 'Standard',
814 1 => 'Nostalgia',
815 2 => 'CologneBlue');
816 # if phptal is enabled we should have monobook skin that
817 # superseed the good old SkinStandard.
818 if ( isset( $skinNames['monobook'] ) ) {
819 $fallback[0] = 'MonoBook';
822 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
823 $sn = $fallback[$userSkin];
824 } else {
825 $sn = 'Standard';
827 } else {
828 # The user skin is available
829 $sn = $skinNames[$userSkin];
832 # Grab the skin class and initialise it. Each skin checks for PHPTal
833 # and will not load if it's not enabled.
834 require_once( $IP.'/skins/'.$sn.'.php' );
836 # Check if we got if not failback to default skin
837 $className = 'Skin'.$sn;
838 if( !class_exists( $className ) ) {
839 # DO NOT die if the class isn't found. This breaks maintenance
840 # scripts and can cause a user account to be unrecoverable
841 # except by SQL manipulation if a previously valid skin name
842 # is no longer valid.
843 $className = 'SkinStandard';
844 require_once( $IP.'/skins/Standard.php' );
846 $this->mSkin =& new $className;
847 wfProfileOut( $fname );
849 return $this->mSkin;
852 /**#@+
853 * @param string $title Article title to look at
857 * Check watched status of an article
858 * @return bool True if article is watched
860 function isWatched( $title ) {
861 $wl = WatchedItem::fromUserTitle( $this, $title );
862 return $wl->isWatched();
866 * Watch an article
868 function addWatch( $title ) {
869 $wl = WatchedItem::fromUserTitle( $this, $title );
870 $wl->addWatch();
871 $this->invalidateCache();
875 * Stop watching an article
877 function removeWatch( $title ) {
878 $wl = WatchedItem::fromUserTitle( $this, $title );
879 $wl->removeWatch();
880 $this->invalidateCache();
884 * Clear the user's notification timestamp for the given title.
885 * If e-notif e-mails are on, they will receive notification mails on
886 * the next change of the page if it's watched etc.
888 function clearNotification( $title ) {
889 $userid = $this->getId();
890 if ($userid==0)
891 return;
892 $dbw =& wfGetDB( DB_MASTER );
893 $success = $dbw->update( 'watchlist',
894 array( /* SET */
895 'wl_notificationtimestamp' => 0
896 ), array( /* WHERE */
897 'wl_title' => $title->getDBkey(),
898 'wl_namespace' => $title->getNamespace(),
899 'wl_user' => $this->getId()
900 ), 'User::clearLastVisited'
904 /**#@-*/
907 * Resets all of the given user's page-change notification timestamps.
908 * If e-notif e-mails are on, they will receive notification mails on
909 * the next change of any watched page.
911 * @param int $currentUser user ID number
912 * @access public
914 function clearAllNotifications( $currentUser ) {
915 if( $currentUser != 0 ) {
917 $dbw =& wfGetDB( DB_MASTER );
918 $success = $dbw->update( 'watchlist',
919 array( /* SET */
920 'wl_notificationtimestamp' => 0
921 ), array( /* WHERE */
922 'wl_user' => $currentUser
923 ), 'UserMailer::clearAll'
926 # we also need to clear here the "you have new message" notification for the own user_talk page
927 # This is cleared one page view later in Article::viewUpdates();
932 * @access private
933 * @return string Encoding options
935 function encodeOptions() {
936 $a = array();
937 foreach ( $this->mOptions as $oname => $oval ) {
938 array_push( $a, $oname.'='.$oval );
940 $s = implode( "\n", $a );
941 return $s;
945 * @access private
947 function decodeOptions( $str ) {
948 $a = explode( "\n", $str );
949 foreach ( $a as $s ) {
950 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
951 $this->mOptions[$m[1]] = $m[2];
956 function setCookies() {
957 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
958 if ( 0 == $this->mId ) return;
959 $this->loadFromDatabase();
960 $exp = time() + $wgCookieExpiration;
962 $_SESSION['wsUserID'] = $this->mId;
963 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
965 $_SESSION['wsUserName'] = $this->mName;
966 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
968 $_SESSION['wsToken'] = $this->mToken;
969 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
970 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
971 } else {
972 setcookie( $wgDBname.'Token', '', time() - 3600 );
977 * Logout user
978 * It will clean the session cookie
980 function logout() {
981 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
982 $this->loadDefaults();
983 $this->setLoaded( true );
985 $_SESSION['wsUserID'] = 0;
987 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
988 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
990 # Remember when user logged out, to prevent seeing cached pages
991 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
995 * Save object settings into database
997 function saveSettings() {
998 global $wgMemc, $wgDBname;
999 $fname = 'User::saveSettings';
1001 $dbw =& wfGetDB( DB_MASTER );
1002 if ( ! $this->getNewtalk() ) {
1003 # Delete the watchlist entry for user_talk page X watched by user X
1004 $dbw->delete( 'watchlist',
1005 array( 'wl_user' => $this->mId,
1006 'wl_title' => $this->getTitleKey(),
1007 'wl_namespace' => NS_USER_TALK ),
1008 $fname );
1009 if( !$this->mId ) {
1010 # Anon users have a separate memcache space for newtalk
1011 # since they don't store their own info. Trim...
1012 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1016 if ( 0 == $this->mId ) { return; }
1018 $dbw->update( 'user',
1019 array( /* SET */
1020 'user_name' => $this->mName,
1021 'user_password' => $this->mPassword,
1022 'user_newpassword' => $this->mNewpassword,
1023 'user_real_name' => $this->mRealName,
1024 'user_email' => $this->mEmail,
1025 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp),
1026 'user_options' => $this->encodeOptions(),
1027 'user_touched' => $dbw->timestamp($this->mTouched),
1028 'user_token' => $this->mToken
1029 ), array( /* WHERE */
1030 'user_id' => $this->mId
1031 ), $fname
1033 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights ),
1034 'ur_user='. $this->mId, $fname );
1035 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1037 // delete old groups
1038 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId), $fname);
1040 // save new ones
1041 foreach ($this->mGroups as $group) {
1042 $dbw->replace( 'user_groups',
1043 array(array('ug_user','ug_group')),
1044 array(
1045 'ug_user' => $this->mId,
1046 'ug_group' => $group
1047 ), $fname
1054 * Checks if a user with the given name exists, returns the ID
1056 function idForName() {
1057 $fname = 'User::idForName';
1059 $gotid = 0;
1060 $s = trim( $this->mName );
1061 if ( 0 == strcmp( '', $s ) ) return 0;
1063 $dbr =& wfGetDB( DB_SLAVE );
1064 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1065 if ( $id === false ) {
1066 $id = 0;
1068 return $id;
1072 * Add user object to the database
1074 function addToDatabase() {
1075 $fname = 'User::addToDatabase';
1076 $dbw =& wfGetDB( DB_MASTER );
1077 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1078 $dbw->insert( 'user',
1079 array(
1080 'user_id' => $seqVal,
1081 'user_name' => $this->mName,
1082 'user_password' => $this->mPassword,
1083 'user_newpassword' => $this->mNewpassword,
1084 'user_email' => $this->mEmail,
1085 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp),
1086 'user_real_name' => $this->mRealName,
1087 'user_options' => $this->encodeOptions(),
1088 'user_token' => $this->mToken
1089 ), $fname
1091 $this->mId = $dbw->insertId();
1092 $dbw->insert( 'user_rights',
1093 array(
1094 'ur_user' => $this->mId,
1095 'ur_rights' => implode( ',', $this->mRights )
1096 ), $fname
1099 foreach ($this->mGroups as $group) {
1100 $dbw->insert( 'user_groups',
1101 array(
1102 'ug_user' => $this->mId,
1103 'ug_group' => $group
1104 ), $fname
1109 function spreadBlock() {
1110 global $wgIP;
1111 # If the (non-anonymous) user is blocked, this function will block any IP address
1112 # that they successfully log on from.
1113 $fname = 'User::spreadBlock';
1115 wfDebug( "User:spreadBlock()\n" );
1116 if ( $this->mId == 0 ) {
1117 return;
1120 $userblock = Block::newFromDB( '', $this->mId );
1121 if ( !$userblock->isValid() ) {
1122 return;
1125 # Check if this IP address is already blocked
1126 $ipblock = Block::newFromDB( $wgIP );
1127 if ( $ipblock->isValid() ) {
1128 # Just update the timestamp
1129 $ipblock->updateTimestamp();
1130 return;
1133 # Make a new block object with the desired properties
1134 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1135 $ipblock->mAddress = $wgIP;
1136 $ipblock->mUser = 0;
1137 $ipblock->mBy = $userblock->mBy;
1138 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1139 $ipblock->mTimestamp = wfTimestampNow();
1140 $ipblock->mAuto = 1;
1141 # If the user is already blocked with an expiry date, we don't
1142 # want to pile on top of that!
1143 if($userblock->mExpiry) {
1144 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1145 } else {
1146 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1149 # Insert it
1150 $ipblock->insert();
1154 function getPageRenderingHash() {
1155 global $wgContLang;
1156 if( $this->mHash ){
1157 return $this->mHash;
1160 // stubthreshold is only included below for completeness,
1161 // it will always be 0 when this function is called by parsercache.
1163 $confstr = $this->getOption( 'math' );
1164 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1165 $confstr .= '!' . $this->getOption( 'editsection' );
1166 $confstr .= '!' . $this->getOption( 'date' );
1167 $confstr .= '!' . $this->getOption( 'numberheadings' );
1168 $confstr .= '!' . $this->getOption( 'language' );
1169 $confstr .= '!' . $this->getOption( 'thumbsize' );
1170 // add in language specific options, if any
1171 $extra = $wgContLang->getExtraHashOptions();
1172 $confstr .= $extra;
1174 $this->mHash = $confstr;
1175 return $confstr ;
1178 function isAllowedToCreateAccount() {
1179 global $wgWhitelistAccount;
1180 $allowed = false;
1182 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1183 foreach ($wgWhitelistAccount as $right => $ok) {
1184 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1185 $allowed |= ($ok && $userHasRight);
1187 return $allowed;
1191 * Set mDataLoaded, return previous value
1192 * Use this to prevent DB access in command-line scripts or similar situations
1194 function setLoaded( $loaded ) {
1195 return wfSetVar( $this->mDataLoaded, $loaded );
1199 * Get this user's personal page title.
1201 * @return Title
1202 * @access public
1204 function getUserPage() {
1205 return Title::makeTitle( NS_USER, $this->mName );
1209 * Get this user's talk page title.
1211 * @return Title
1212 * @access public
1214 function getTalkPage() {
1215 $title = $this->getUserPage();
1216 return $title->getTalkPage();
1220 * @static
1222 function getMaxID() {
1223 $dbr =& wfGetDB( DB_SLAVE );
1224 return $dbr->selectField( 'user', 'max(user_id)', false );
1228 * Determine whether the user is a newbie. Newbies are either
1229 * anonymous IPs, or the 1% most recently created accounts.
1230 * Bots and sysops are excluded.
1231 * @return bool True if it is a newbie.
1233 function isNewbie() {
1234 return $this->mId > User::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() || $this->getID() == 0;
1238 * Check to see if the given clear-text password is one of the accepted passwords
1239 * @param string $password User password.
1240 * @return bool True if the given password is correct otherwise False.
1242 function checkPassword( $password ) {
1243 global $wgAuth;
1244 $this->loadFromDatabase();
1246 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1247 return true;
1248 } elseif( $wgAuth->strict() ) {
1249 /* Auth plugin doesn't allow local authentication */
1250 return false;
1252 $ep = $this->encryptPassword( $password );
1253 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1254 return true;
1255 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1256 $this->mEmailAuthenticationtimestamp = wfTimestampNow();
1257 $this->mNewpassword = ''; # use the temporary one-time password only once: clear it now !
1258 $this->saveSettings();
1259 return true;
1260 } elseif ( function_exists( 'iconv' ) ) {
1261 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1262 # Check for this with iconv
1263 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1264 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1265 return true;
1268 return false;
1272 * Initialize (if necessary) and return a session token value
1273 * which can be used in edit forms to show that the user's
1274 * login credentials aren't being hijacked with a foreign form
1275 * submission.
1277 * @param mixed $salt - Optional function-specific data for hash.
1278 * Use a string or an array of strings.
1279 * @return string
1280 * @access public
1282 function editToken( $salt = '' ) {
1283 if( !isset( $_SESSION['wsEditToken'] ) ) {
1284 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1285 $_SESSION['wsEditToken'] = $token;
1286 } else {
1287 $token = $_SESSION['wsEditToken'];
1289 if( is_array( $salt ) ) {
1290 $salt = implode( '|', $salt );
1292 return md5( $token . $salt );
1296 * Check given value against the token value stored in the session.
1297 * A match should confirm that the form was submitted from the
1298 * user's own login session, not a form submission from a third-party
1299 * site.
1301 * @param string $val - the input value to compare
1302 * @param string $salt - Optional function-specific data for hash
1303 * @return bool
1304 * @access public
1306 function matchEditToken( $val, $salt = '' ) {
1307 return ( $val == $this->editToken( $salt ) );