<?php
/**
#	Project: PHPDISK File Storage Solution
#	This is NOT a freeware, use is subject to license terms.
#
#	Site: http://www.phpdisk.com
#
#	$Id: login.php 9 2011-06-01 01:09:13Z along $
#
#	Copyright (C) 2008-2011 PHPDisk Team. All Rights Reserved.
#
*/
include '../../includes/commons.inc.php';

$username = rawurldecode(trim(gpc('user','P','')));
$password = trim(gpc('pwd','P',''));
$hash = trim(gpc('hash','P',''));
$username = !is_utf8() ? convert_str('utf-8','gbk',$username) : $username;

if(!$settings['open_client']){
	echo 'client_not_open';
	exit;
}
$client_info = @$db->result_first("select client_info from {$tpf}client_set limit 1");
if($client_info){
	$ci = unserialize($client_info);
	$ci['server_key'] = pd_encode($ci['server_key'],'DECODE');
	$ci['server_store_path'] = pd_encode($ci['server_store_path'],'DECODE');
	$ci['ftp_host'] = pd_encode($ci['ftp_host'],'DECODE');
	$ci['ftp_port'] = strval(pd_encode($ci['ftp_port'],'DECODE'));
	$ci['ftp_user'] = pd_encode($ci['ftp_user'],'DECODE');
	$ci['ftp_pass'] = pd_encode($ci['ftp_pass'],'DECODE');
	$ci['ftp_pasv'] = $ci['ftp_pasv'] ? 'true' : 'false';
}

if($hash != strtoupper(md5($ci['server_key']))){
	echo 'client_hash_key_error';
	exit;
}
if(strpos(strtoupper($_SERVER['HTTP_USER_AGENT']),'ICS')===false){
	echo 'client_agent_error';
	exit;
}
if(!$username){
	echo 'client_username_error';
	exit;
}else{
	$username = $db->escape($username);
}

$rs = $db->fetch_one_array("select userid,username,is_locked,is_activated,password from {$tpf}users where username='$username' limit 1");
if(!$rs){
	echo 'client_username_error';
	exit;
}elseif($rs['is_locked']){
	echo 'client_user_locked';
	exit;
}elseif($settings['user_active'] && $rs['is_activated']<>1){
	echo 'client_user_not_active';
	exit;
}else{
	if($password !=strtoupper($rs['password'])){
		echo 'client_password_error';
		exit;
	}else{
		$tmp_username = is_utf8() ? convert_str('utf-8','gbk',$rs['username']) : $rs['username'];
		$mydir_s = PHPDISK_ROOT.$ci['server_store_path'].'/';
		$mydir_s2 = $mydir_s.$tmp_username.'/';
		make_dir($mydir_s2,0);

		echo '1'.LF;
		echo my_encode($ci['ftp_user']).LF;
		echo my_encode($ci['ftp_pass']).LF;
		echo my_encode($tmp_username).LF;
		echo my_encode($ci['ftp_host']).LF;
		echo my_encode($ci['ftp_port']).LF;
		echo my_encode($settings['phpdisk_url'].'plugins/client/opfile.php').LF;
		echo my_encode($settings['phpdisk_url'].$ci['server_store_path']).LF;
		echo my_encode($ci['ftp_pasv']).LF;
		exit;
	}
}

function my_encode($str,$key='phpdisk'){
	global $ci;
	$key = $ci['server_key'] ? $ci['server_key'] : $key;
	$keyPos = 0;
	$keyLen = strlen($key);
	$offset = mt_rand(0,256);
	$dest = substr(sprintf('%02X',$offset),0,2);

	for($i=0;$i<strlen($str);$i++){
		$srcAsc = (ord($str[$i])+$offset) % 255;
		$keyPos = ($keyPos < $keyLen) ? $keyPos+1 : 1;
		$srcAsc = $srcAsc ^ ord($key[$keyPos-1]);
		$dest = $dest.substr(sprintf('%02X',$srcAsc),0,2);
		$offset = $srcAsc;
	}
	return base64_encode($dest);
}
?>