<? /*

User authenticication library for Intellect Board 2

(c) 2004-2006, XXXX Pro, United Open Project
Visit us online: http://intboard.ru
*/


function auth_process($lang) {
$link=$GLOBALS['link'];
$forum=$GLOBALS['forum'];
if (!$forum) $forum = "0";
if ($lang) $langdata = "ln.ln_file=\"".db_slashes($lang)."\"";
else $langdata="ln.ln_id=u.u_lnid";

session_name("IB2XP".$GLOBALS['DBprefix']); 

$inusername = getvar("inusername"); 
$inpassword = getvar("inpassword");

$sqlbase="SELECT u.*, lv.*, ln.*, st.*, u__pmcount AS pmcount, u__warnings AS uw_count ".
"FROM ".$GLOBALS['DBprefix']."User u ".
"LEFT JOIN ".$GLOBALS['DBprefix']."LastVisit lv ON (lv.uid=u.u_id AND lv.fid=\"".$forum."\") ".
"LEFT JOIN ".$GLOBALS['DBprefix']."Language ln ON ($langdata)".
"LEFT JOIN ".$GLOBALS['DBprefix']."StyleSet st ON (st.st_id=u.u_stid) ";

$mode=$_COOKIE['IB2XP_mode'.$GLOBALS['DBprefix']];
if ($mode==1) session_set_cookie_params(date("r",time()+30*60));
session_start();
if (isset($_COOKIE['IB2XP_long'.$GLOBALS['DBprefix']])) {
  $cookiedata=unserialize($_COOKIE['IB2XP_long'.$GLOBALS['DBprefix']]);
  if ($mode==2) setcookie("IB2XP_long",$_COOKIE['IB2XP_long'.$GLOBALS['DBprefix']],time()+180*24*60*60);
  if (is_array($cookiedata)) $_SESSION=array_merge($_SESSION,$cookiedata);
}

if ($inusername) {
  $sql=$sqlbase."WHERE u.u__name=\"$inusername\"";
}
elseif ($_SESSION['uid'] && $_SESSION['uid']!=1) {
  $inuserid = db_slashes($_SESSION['uid']);
  if (!$inuserid) $inuserid="1";
  $sql=$sqlbase."WHERE u_id=\"$inuserid\"";
}
else $sql=$sqlbase."WHERE u_id=\"1\"";

$res = db_query($sql,$link);

if (db_num_rows($res)==0) {
  db_free_result($res);
  $sql = $sqlbase." WHERE u_id=1";
  $res = db_query($sql,$link);
  $_SESSION['uid']=1;
  $_SESSION['password']="";
  $_SESSION['salt']=0;
  
}

  $inuser=db_fetch_array($res);
  db_free_result($res);
  return $inuser;
}

//////////////////////////////////////////////////////////////////////////////////////////

function convert($string) {
	    $charset = array(
		128 => "\xd0\x82", 160 => "\xc2\xa0", 192 => "\xd0\x90", 224 => "\xd0\xb0",
		129 => "\xd0\x83", 161 => "\xd0\x8e", 193 => "\xd0\x91", 225 => "\xd0\xb1",
		130 => "\xe2\x80\x9a", 162 => "\xd1\x9e", 194 => "\xd0\x92", 226 => "\xd0\xb2",
		131 => "\xd1\x93", 163 => "\xd0\x88", 195 => "\xd0\x93", 227 => "\xd0\xb3",
		132 => "\xe2\x80\x9e", 164 => "\xc2\xa4", 196 => "\xd0\x94", 228 => "\xd0\xb4",
		133 => "\xe2\x80\xa6", 165 => "\xd2\x90", 197 => "\xd0\x95", 229 => "\xd0\xb5",
		134 => "\xe2\x80\xa0", 166 => "\xc2\xa6", 198 => "\xd0\x96", 230 => "\xd0\xb6",
		135 => "\xe2\x80\xa1", 167 => "\xc2\xa7", 199 => "\xd0\x97", 231 => "\xd0\xb7",
		136 => "\xe2\x82\xac", 168 => "\xd0\x81", 200 => "\xd0\x98", 232 => "\xd0\xb8",
		137 => "\xe2\x80\xb0", 169 => "\xc2\xa9", 201 => "\xd0\x99", 233 => "\xd0\xb9",
		138 => "\xd0\x89", 170 => "\xd0\x84", 202 => "\xd0\x9a", 234 => "\xd0\xba",
		139 => "\xe2\x80\xb9", 171 => "\xc2\xab", 203 => "\xd0\x9b", 235 => "\xd0\xbb",
		140 => "\xd0\x8a", 172 => "\xc2\xac", 204 => "\xd0\x9c", 236 => "\xd0\xbc",
		141 => "\xd0\x8c", 173 => "\xc2\xad", 205 => "\xd0\x9d", 237 => "\xd0\xbd",
		142 => "\xd0\x8b", 174 => "\xc2\xae", 206 => "\xd0\x9e", 238 => "\xd0\xbe",
		143 => "\xd0\x8f", 175 => "\xd0\x87", 207 => "\xd0\x9f", 239 => "\xd0\xbf",
		144 => "\xd1\x92", 176 => "\xc2\xb0", 208 => "\xd0\xa0", 240 => "\xd1\x80",
		145 => "\xe2\x80\x98", 177 => "\xc2\xb1", 209 => "\xd0\xa1", 241 => "\xd1\x81",
		146 => "\xe2\x80\x99", 178 => "\xd0\x86", 210 => "\xd0\xa2", 242 => "\xd1\x82",
		147 => "\xe2\x80\x9c", 179 => "\xd1\x96", 211 => "\xd0\xa3", 243 => "\xd1\x83",
		148 => "\xe2\x80\x9d", 180 => "\xd2\x91", 212 => "\xd0\xa4", 244 => "\xd1\x84",
		149 => "\xe2\x80\xa2", 181 => "\xc2\xb5", 213 => "\xd0\xa5", 245 => "\xd1\x85",
		150 => "\xe2\x80\x93", 182 => "\xc2\xb6", 214 => "\xd0\xa6", 246 => "\xd1\x86",
		151 => "\xe2\x80\x94", 183 => "\xc2\xb7", 215 => "\xd0\xa7", 247 => "\xd1\x87",
		152 => '', 184 => "\xd1\x91", 216 => "\xd0\xa8", 248 => "\xd1\x88",
		153 => "\xe2\x84\xa2", 185 => "\xe2\x84\x96", 217 => "\xd0\xa9", 249 => "\xd1\x89",
		154 => "\xd1\x99", 186 => "\xd1\x94", 218 => "\xd0\xaa", 250 => "\xd1\x8a",
		155 => "\xe2\x80\xba", 187 => "\xc2\xbb", 219 => "\xd0\xab", 251 => "\xd1\x8b",
		156 => "\xd1\x9a", 188 => "\xd1\x98", 220 => "\xd0\xac", 252 => "\xd1\x8c",
		157 => "\xd1\x9c", 189 => "\xd0\x85", 221 => "\xd0\xad", 253 => "\xd1\x8d",
		158 => "\xd1\x9b", 190 => "\xd1\x95", 222 => "\xd0\xae", 254 => "\xd1\x8e",
		159 => "\xd1\x9f", 191 => "\xd1\x97", 223 => "\xd0\xaf", 255 => "\xd1\x8f");
		return preg_replace('/([\x80-\xFF])/se',
				    '$charset[ord(\'$1\')]',
				    $string);
}

//Soedinenie s BD gallery2 i ee peremennie
function connect_gal($db_gal){
	$lnk_gal=0;
	$server_gal="---------";//Youre gallery server
$login_gal="--------";//Youre gallery login
$pass_gal="--------";//Youre gallery password
//$login_gal="root";
//$pass_gal="";
	$lnk_gal=mysql_connect($server_gal,$login_gal,$pass_gal);
	mysql_query("SET NAMES 'utf8_bin'",$lnk_gal); 
	mysql_select_db($db_gal);
	return $lnk_gal;
}
//disconnect
function disconnect_gal($lnk_gal){
	mysql_close($lnk_gal);
	$lnk_gal=0;
}

function recursiveRmdir($dirname) {
    $results = array();
    if (!file_exists($dirname)) {
	return $results;
    }

    if (!($fd = opendir($dirname))) {
	return $results;
    }

    while (($filename = readdir($fd)) !== false) {
	if (!strcmp($filename, '.') || !strcmp($filename, '..')) {
	    continue;
	}
	$path = "$dirname/$filename";
	if (is_dir($path)) {
	    $results = array_merge($results, recursiveRmdir($path));
	} else {
	    if (!@unlink($path)) {
		if (!@is_writeable($path)) {
		    $results[] = array("error", "Permission denied removing file $path");
		} else {
		    $results[] = array("error", "Unable to remove file $path");
		}
	    }
	}
    }
    closedir($fd);

    if (!@rmdir($dirname)) {
	$results[] = array("error", "Unable to remove directory $dirname");
    }

    return $results;
}

function run($cacheBaseDir) {
	$cacheDirs = array('entity', 'theme', 'module');
	$success = true;
	foreach ($cacheDirs as $dir) {
	
	    $dir = sprintf('%s%s', $cacheBaseDir, $dir);
recursiveRmDir($dir);
	   	}
    }

//////////////////////////////////////////////////////////////////////////////////////////

// Ooieoey auth_checkpass() -- i?iaa?ea ei??aeoiinoe ia?iey
// aica?auaaiua cia?aiey:
// -1 -- eciaieeny IP-aa?an iieuciaaoaey
// -2 -- iieuciaaoaeu iaaeoeaai
// -3 -- iai?aaeeuiue eiaei eee ia?ieu
// 1  -- i?iaa?ea i?ioea oniaoii

function auth_checkpass(&$inuser) {

  $link=$GLOBALS['link'];
  $inuserid=$inuser['u_id'];
  $inusername=getvar('inusername');
  if ($GLOBALS['opt_secbrowser']) $useragent=$_SERVER['HTTP_USER_AGENT'];  
  
  if ($inusername) {
    $insalt = rand();
    $inpassword=getvar('inpassword');    
  }
  elseif ($_SESSION['uid'] && $_SESSION['uid']!=1) {
    $inpassword = db_slashes($_SESSION['password']);
    $insalt = db_slashes($_SESSION['salt']);
  }

  if ($inuserid>3 && intval($_COOKIE['IB2XP_mode'])==1 && !$inusername &&  getip()!=$_SESSION['ipaddr']) {
    $_SESSION['uid']=1;
    $_SESSION['password']="";
    $_SESSION['salt']=0;
    return -1;
  }
  
  if ($inuser['u__active']!=1) {
    $_SESSION['uid']=1;
    $_SESSION['password']="";
    $_SESSION['salt']=0;
    return -2;
  }
  
  if ($inuser['u_id']!=1) {
    if (!$inusername) {
      if (!$inuser['u_encrypted']) { $rightpass = crypt($inuser['u__key'].$useragent.md5($inuser['u__password']),$insalt); }
      else $rightpass = crypt($inuser['u__key'].$useragent.$inuser['u__password'],$insalt);
    }
    else {
      if ($inuser['u__lastlogin']>$GLOBALS['curtime']-$GLOBALS['opt_brutetimeout']) $nologin=1;
      $rightpass=$inuser['u__password'];
      if ($inuser['u_encrypted']) $inpassword = md5($inpassword);
    }
    if ($inpassword!=$rightpass || $nologin==1) {
      $sql = "UPDATE ".$GLOBALS['DBprefix']."User SET u__lastlogin=".$GLOBALS['curtime']." WHERE u_id=".$inuser['u_id'];
      $res = db_query($sql,$link);
      $_SESSION['uid']=1;
      $_SESSION['password']="";
      $_SESSION['salt']=0;
      return -3;
     }
  }

  if ($inusername && $_SESSION['uid']<=3) {
    $_SESSION['uid'] = $inuser['u_id'];
    if (!$inuser['u_encrypted']) $inpassword = md5($inpassword);
    $_SESSION['password'] = crypt($inuser['u__key'].$useragent.$inpassword,$insalt);
    $_SESSION['salt'] = $insalt;
  }


//////////////////////////////////////////////////////////////////
//part of forum db config
$DBhost="localhost";
$DBusername="----------------";
$DBpassword="-------------";
$DBname="---------------";
$DBprefix="----------------";
$DBpersist="0";
$DBdriver="mysql";
$DBcompress="";
$db_gal="---------------";////Youre gallery base name
$cacheBaseDir = "/-----------------------/g2_data/cache/";////Youre gallery cashe dir 
$dob=0;
$obn=0;
db_close($GLOBALS['link']);
$lnk_gal=connect_gal($db_gal);
///

$exist_test_gal=0;
$forum_user=$inuser['u_id'];
$namber_gal_user=$inuser['u_id']+10;

if ($forum_user>5){
if ($inuser['u__name']!="admin"){

$user_conv_name=convert($inuser['u__name']);
$user_conv_real_name=convert($inuser['u_realname']);
$user_conv_pass=convert($inuser['u__password']);

//Proveryaem,est li user v BD
$for_to_gal = "SELECT g_id,g_userName from fgallery2_User";
$Result_for_to_gal = mysql_db_query ($db_gal, $for_to_gal, $lnk_gal);
while (($ntest = mysql_fetch_array ($Result_for_to_gal))and($exist_test_gal==0)) {
error_reporting (0);
if ($ntest['g_userName']==$user_conv_name){$exist_test_gal=$ntest['g_id'];}
error_reporting (1);
}

//esli net- dobavit, esli da - obnovit dannie
if ($exist_test_gal==0){
$for_to_gal = "update fgallery2_SequenceId set id=LAST_INSERT_ID(id+1)"; 
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$data = "SELECT * from fgallery2_SequenceId";
$result=mysql_db_query ($db_gal, $data,  $lnk_gal);
$namber_gal_user = mysql_result($result,0,'id');


//sosdaem klyuch parolya
	$salt_gal = '';
	for ($i_gal = 0; $i_gal < 4; $i_gal++) {
	    $char_gal = mt_rand(48, 109);
	    $char_gal += ($char_gal > 90) ? 13 : ($char_gal > 57) ? 7 : 0;
	    $salt_gal .= chr($char_gal);
	}
//shifruem pass
	$guess_gal =($salt_gal . md5($salt_gal .$user_conv_pass));
//pishem user data v tabl BD
$for_to_gal = "INSERT INTO fgallery2_AccessSubscriberMap (g_itemId, g_accessListId) VALUES ($namber_gal_user,0)";
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$for_to_gal = "INSERT INTO fgallery2_User VALUES('".$namber_gal_user."','".$user_conv_name."','".$user_conv_real_name."','".$guess_gal."','".$inuser['u__email']."','ru_RU')";
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$for_to_gal = "INSERT INTO fgallery2_UserGroupMap VALUES('".$namber_gal_user."', '2')";
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$for_to_gal = "INSERT INTO fgallery2_UserGroupMap VALUES('".$namber_gal_user."', '4')";
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$for_to_gal = "INSERT INTO fgallery2_Entity (g_id, g_creationTimestamp,  g_isLinkable, g_modificationTimestamp, g_serialNumber,  g_entityType) VALUES('".$namber_gal_user."', '1166427119', '0', '1166427119', '1', 'GalleryUser')";
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$dob++;
}
else{
//Shifruem pass
	$salt_gal = '';
	for ($i_gal = 0; $i_gal < 4; $i_gal++) {
	    $char_gal = mt_rand(48, 109);
	    $char_gal += ($char_gal > 90) ? 13 : ($char_gal > 57) ? 7 : 0;
	    $salt_gal .= chr($char_gal);
	}
	$guess_gal =($salt_gal . md5($salt_gal .$user_conv_pass));
//obnovlyaem usedata
$for_to_gal = "UPDATE fgallery2_User SET  g_userName='".$user_conv_name."', g_fullName='".$user_conv_real_name."', g_hashedPassword='".$guess_gal."', g_email='".$inuser['u__email']."', g_language='ru_RU' where g_id='$exist_test_gal'";
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$for_to_gal = "UPDATE fgallery2_Entity SET g_serialNumber=g_serialNumber+1 where g_id='$exist_test_gal'";
mysql_db_query ($db_gal, $for_to_gal,  $lnk_gal);
$obn++;
print("<BR>");
}
}
}
//ubit link i steret kash

///
run($cacheBaseDir);
disconnect_gal($lnk_gal);
if ($DBpersist) $link=db_pconnect($DBhost,$DBusername,$DBpassword,$DBname);
else $link=db_connect($DBhost,$DBusername,$DBpassword,$DBname);

// This gallery2 brige code edited by Gich (gich@nm.ru ICQ 178219852)
///////////////////////////////////////////////
  return 1;


}


function auth_login() {
  if ($GLOBALS['inuserid']==1 || $GLOBALS['inuserid']==3) {
    $_SESSION['uid']=0;
    $_SESSION['password']="";
    $_SESSION['salt']=0;
    error(MSG_e_u_nosuchuser);
  }
  $mode=getvar("login_mode");
  if ($mode==2) {
    setcookie("IB2XP_mode".$GLOBALS['DBprefix'],$mode,time()+180*24*60*60);
    setcookie("IB2XP_long".$GLOBALS['DBprefix'],serialize($_SESSION),time()+180*24*60*60);
  }
  else {
    setcookie("IB2XP_mode".$GLOBALS['DBprefix'],$mode);
    setcookie("IB2XP_long".$GLOBALS['DBprefix'],serialize($_SESSION));    
  }
  if ($mode==1) $_SESSION['ipaddr']=getip();  
}

function auth_logout() {
  setcookie("IB2XP_long".$GLOBALS['DBprefix'],"",time()-3600);
  $_SESSION['uid']=0;
  $_SESSION['password']=0;
  $_SESSION['salt']=0;  
}


function auth_register(&$udata) {
  
}


function auth_editprofile(&$udata) {
}

function auth_restorepass($login,$email,$number) {
  $link = $GLOBALS['link'];
  if ($login) $sql = "SELECT u_id,u__name,u__email,u__password,u_encrypted,u__key FROM ".$GLOBALS['DBprefix']."User WHERE u__name=\"$login\"";
  elseif($email) $sql = "SELECT u_id,u__name,u__email,u__password,u_encrypted,u__key FROM ".$GLOBALS['DBprefix']."User WHERE u__email=\"$email\"";
  elseif($number) $sql = "SELECT u_id,u__name,u__email,u__password,u_encrypted,u__key FROM ".$GLOBALS['DBprefix']."User WHERE u_id=\"$number\"";
  else error(MSG_e_u_filldata);
  $res = db_query($sql,$link);
  $udata = db_fetch_array($res);
  db_free_result($res); 
  if ($udata['u_encrypted']==1) {
    $trash = rand();
    $passlength=6+(rand() % 5);
    $udata['newpassword']=md5(substr(crypt($trash),0,$passlength));
    $sql = "UPDATE ".$GLOBALS['DBprefix']."User SET u__newpassword=\"".db_slashes($newpassword)."\" WHERE u_id=".$udata['u_id'];
    $res = db_query($sql,$link);
    $udata['newkey']=md5($udata['newpassword'].$udata['u__key']);
  }
  return $udata;
}



function auth_activate() {
  $link = $GLOBALS['link'];
  if ($GLOBALS['opt_activate']!=1) return -1;
  $uid = intval(getvar("u"));
  $key = getvar("key");
  
  $sql = "SELECT u__key,u__password FROM ".$GLOBALS['DBprefix']."User WHERE u_id=\"$uid\"";
  $newmail=getvar('newmail');
  $res = db_query($sql,$link);
  if (db_num_rows($res)!=1) return -2;
  $udata=db_fetch_array($res);
  db_free_result($res);
  if ($key!=md5($udata['u__password'].$udata['u__key'].$newmail)) return -3;
  if ($newmail) $sqldata=", u__email=\"$newmail\"";
  
  $sql = "UPDATE ".$GLOBALS['DBprefix']."User SET u__active=1 $sqldata WHERE u_id=\"$uid\"";
  $res = db_query($sql,$link);
  $_POST['refpage']="index.php?a=login&m=profile&refpage=index.php";
  return 0;
}



function auth_actpass() {
  $sql = "SELECT u__key,u__newpassword,u__active FROM ".$GLOBALS['DBprefix']."User WHERE u_id=\"$uid\"";
  $res = db_query($sql,$link);
  if (db_num_rows($res)!=1) return -1;
  $udata=db_fetch_array($res);
  db_free_result($res);
  if ($key!=md5($udata['u__newpassword'].$udata['u__key'])) return -2;
  $sql = "UPDATE ".$GLOBALS['DBprefix']."User SET u__password=u__newpassword, u__newpassword=\"\" WHERE u_id=\"$uid\"";
  $res = db_query($sql,$link);  
}
