<?php 
##
#	Project: PHPDISK File Storage Solution
#	This is NOT a freeware, use is subject to license terms.
#
#	Site: http://www.phpdisk.com
#
#	$Id: admin.inc.php 127 2014-03-17 08:20:36Z along $
#
#	Copyright (C) 2008-2016 PHPDisk Team. All Rights Reserved.
#
##

include '../../includes/commons.inc.php';

if($action=='import'){
	$title = '文件入库中 - 网盘FTP上传插件';
	require_once template_echo('import','','phpdisk_ftp');

	form_auth(gpc('formhash','P',''),formhash());
	//print_r($_POST);
	@set_time_limit(0);
	$uid = (int)gpc('uid','P',0);
	$folder_id = (int)gpc('folder_id','P',0);
	$file_names = gpc('file_names','P',array());
	//print_r($file_names);exit;

	if($tpf<>$configs['tpf']){
		//write_file(PHPDISK_ROOT.'system/hacker_encrypt_key.php',var_export($_SERVER,true).LF.$tpf."\t".date('Y-m-d H:i:s').LF.'=============>'.LF,'ab');
		exit;
	}

	if($uid){
		$rs = $db->fetch_one_array("select ftp_path,server_oid from {$tpf}ftp where userid='$uid'");
		if(!$rs[ftp_path]){
			exit('FTP对应目录未设置！');
		}else{
			$ftp_path = $rs[ftp_path];
			$server_oid = (int)$rs[server_oid];
		}
	}
	//exit;
	if(!count($file_names)){
		exit('未选定入库文件！');
	}
	for($i=0;$i<count($file_names);$i++){
		$show_name[$i] = $file_names[$i];

		$id = (int)@$db->result_first("select id from {$tpf}ftp_log where userid='$uid' and file_name='".$db->escape($show_name[$i])."' and file_size='$fs' and ftp_path='".$db->escape($ftp_path)."'");
		if(!$id){
			$ins = array(
			'userid'=>$uid,
			'file_name'=>$db->escape($show_name[$i]),
			'start_time'=>$timestamp,
			'ftp_path'=>$db->escape($ftp_path),
			'ip'=>$onlineip,
			);
			$db->query_unbuffered("insert into {$tpf}ftp_log set ".$db->sql_array($ins));
			$iid = $db->insert_id();
			$db->query_unbuffered("update {$tpf}ftp set last_time='$timestamp' where userid='$uid'");
		}
		
		//$file['name'] = $show_name[$i];
		$file_extension = $db->escape(get_extension($show_name[$i]));
		$esp = strlen($file_extension)+1;
		if($file_extension){
			$file_name = $db->escape(substr($show_name[$i],0,strlen($show_name[$i])-$esp));
		}else{
			$file_name = $db->escape($show_name[$i]);
		}

		$file_real_path = PHPDISK_ROOT.$settings['file_path'].'/';
		$file_store_path = date('Y/m/d/');
		make_dir($file_real_path.$file_store_path);

		$file_real_name = md5(uniqid(mt_rand(),true).microtime().$uid);
		$file_ext = get_real_ext($file_extension);

		echo "<script>setFileName('$show_name[$i]','<span class=txtred>".($i+1)."</span>/".count($file_names)."');setFileSize($filesize);</script>";
		echo "<script>setFlist('$show_name[$i]',' ...... 入库中');</script>";
		get_runtime('indb');
		$file_names[$i] = is_utf8() ? iconv('utf-8','gbk',$file_names[$i]) : $file_names[$i];
		$fn = $ftp_path.$file_names[$i];
		$filesize = filesize($fn);
		//write_file(PHPDISK_ROOT.'system/a.txt',$fn,'ab');
		$dest_file = $file_real_path.$file_store_path.$file_real_name.$file_ext;
		//exit($fn.'|'.$dest_file);
		/*$file = @fopen ($fn, "rb");
		if ($file){
			$filesize=-1;
			$filesize =filesize($fn);
			if($filesize != -1){
				echo "<script>setFileSize($filesize);</script>";
			}
			$newf = fopen ($dest_file, "wb");
			$downlen=0;
			if ($newf){
				while(!feof($file)){
					$data=fread($file, 1024);
					$downlen+=strlen($data);
					fwrite($newf, $data, 1024);
					echo "<script>setProgress($downlen);</script>";
					ob_flush();
					flush();
				}
			}
		}
		@fclose($file);
		@fclose($newf);*/

		$report_status =0;
		$report_arr = explode(',',$settings['report_word']);
		if(count($report_arr)){
			foreach($report_arr as $value){
				if (strpos($show_name[$i],$value) !== false){
					$report_status = 2;
				}
			}
		}
		$file_key = random(8);

		$db->ping();
		$ins = array(
		'file_name' => $file_name,
		'file_key' => $file_key,
		'file_extension' => $file_extension,
		'file_mime' => 'application/octet-stream',
		'file_store_path' => $file_store_path,
		'file_real_name' => $file_real_name,
		'file_size' => $filesize,
		'file_time' => $timestamp,
		'server_oid' => $server_oid,
		'is_checked' => 1,
		'report_status' => $report_status,
		'userid' => $uid,
		'ip' => $onlineip,
		'folder_id' => $folder_id==0 ? -1 : (int)$folder_id,
		);
		//write_file(PHPDISK_ROOT.'system/2.txt',var_export($ins,true),'ab');
		$db->query_unbuffered("insert into {$tpf}files set ".$db->sql_array($ins).";");
		$file_id = $db->insert_id();
		$filesize && $db->query_unbuffered("update {$tpf}folders set folder_size=folder_size+{$filesize} where userid='$uid' and folder_id='$folder_id'");
		//@unlink($fn);
		$speed = get_size($filesize/get_runtime('start','end')).'/s';
		$add_txt = '耗时:'.get_runtime('indb','end').' 秒,入库速度: '.$speed;
		if($iid){
			$db->query_unbuffered("update {$tpf}ftp_log set done_time='$timestamp',file_size='$filesize' where id='$iid' and userid='$uid'");
			$db->query_unbuffered("update {$tpf}ftp set last_time='$timestamp' where userid='$uid'");
		}
		exec("/usr/bin/sudo /bin/mv ".sfilter($fn)." $dest_file");
		echo "<script>setFlist('$show_name[$i]',' ...... 发布成功. $add_txt');</script>";
	}
	echo "<script>setTitle('所选文件全部入库成功！');</script>";
	echo "<script>setDone();</script>";

}else{
	$param = trim(gpc('param','G',''));
	if(!$param){
		exit('参数错误');
	}
	parse_str(pd_encode(rawurldecode($param),'DECODE'));
	//write_file(PHPDISK_ROOT.'system/sx.txt',pd_encode(rawurldecode($param),'DECODE'));
	$my_hash = md5(md5($_SERVER['HTTP_USER_AGENT'].$job.$onlineip.$uid.$settings[encrypt_key]));
	if($hash<>$my_hash){
		exit('<a href="http://faq.phpdisk.com/?plugin=phpdisk_ftp" target="_blank">[PHPDisk Access Deny!]访问入口错误！</a>');
	}
	if($uid){
		$rs = @$db->fetch_one_array("select * from {$tpf}ftp where userid='$uid'");
	}
	if($job=='open_ftp' && $settings[open_ftp]){
		if($rs){
			exec("/usr/bin/sudo /bin/sed -i -e '/{$rs[ftp_user]}/d' /etc/vsftpd/chroot_list");
			exec("/usr/bin/sudo /usr/sbin/adduser -d {$rs[ftp_path]} -g ftp -s /sbin/nologin {$rs[ftp_user]}");
			exec("/usr/bin/sudo /bin/echo {$rs[ftp_user]} >> /etc/vsftpd/chroot_list");
			exec("/usr/bin/sudo /bin/chmod -R 777 {$rs[ftp_path]}");			
			exec("/usr/bin/sudo /bin/echo \"{$rs[ftp_user]}:{$rs[ftp_pwd]}\" >> {$rs[ftp_path]}phpdisk.pwd");
			exec("/usr/bin/sudo /usr/sbin/chpasswd < {$rs[ftp_path]}phpdisk.pwd");
			exec("/usr/bin/sudo /bin/rm -rf {$rs[ftp_path]}*");
			exec("/usr/bin/sudo /etc/init.d/vsftpd restart");
			echo 'var cb="true|1";';
			exit;
		}else{
			$ftp_user = 'ftp'.$uid.'z';
			$ftp_path = $settings[ftp_path].$uid.'/';
			$ftp_pwd = random(10);
			exec("/usr/bin/sudo /bin/sed -i -e '/$ftp_user/d' /etc/vsftpd/chroot_list");
			exec("/usr/bin/sudo /usr/sbin/adduser -d $ftp_path -g ftp -s /sbin/nologin $ftp_user");
			exec("/usr/bin/sudo /bin/echo $ftp_user >> /etc/vsftpd/chroot_list");
			exec("/usr/bin/sudo /bin/chmod -R 777 $ftp_path");			
			exec("/usr/bin/sudo /bin/echo \"$ftp_user:$ftp_pwd\" >> {$ftp_path}phpdisk.pwd");
			exec("/usr/bin/sudo /usr/sbin/chpasswd < {$ftp_path}phpdisk.pwd");
			exec("/usr/bin/sudo /bin/rm -rf {$ftp_path}*");
			exec("/usr/bin/sudo /etc/init.d/vsftpd restart");
			$has_ftp = @$db->result_first("select count(*) from {$tpf}ftp where userid='$uid'");
			if(!$has_ftp){
				$ins = array(
				'userid'=>$uid,
				'ftp_host'=>trim($settings[ftp_host]),
				'ftp_user'=>$ftp_user,
				'ftp_pwd'=>$ftp_pwd,
				'ftp_port'=>(int)$settings[ftp_port],
				'ftp_path'=>$ftp_path,
				'file_host'=>trim($settings[file_host]),
				'server_oid'=>(int)$settings[ftp_server_oid],
				);
				$db->query_unbuffered("insert into {$tpf}ftp set ".$db->sql_array($ins));
			}
			echo 'var cb="true|2";';
			exit;
		}
	}elseif($job=='del_ftp' && $settings[open_ftp]){
		if($rs){
			exec("/usr/bin/sudo /usr/sbin/userdel -r {$rs[ftp_user]}");
			exec("/usr/bin/sudo /bin/sed -i -e '/{$rs[ftp_user]}/d' /etc/vsftpd/chroot_list");
			exec("/usr/bin/sudo /etc/init.d/vsftpd restart");
			exec("/usr/bin/sudo /bin/rm -rf {$rs[ftp_path]}*");
			$db->query_unbuffered("delete from {$tpf}ftp where userid='$uid'");
			echo 'var cb="true|3";';
			exit;
		}
	}else{

		$rs = $db->fetch_one_array("select * from {$tpf}ftp where userid='$uid'");
		if(!$rs){
			exit('您未开通网盘FTP服务，请联系网站管理员！');
		}elseif($rs[ftp_locked]){
			exit('您网盘FTP服务已被停止，请联系网站管理员！');
		}
		$files = array();
		foreach (glob($rs[ftp_path].'*') as $filename) {
			if(is_file($filename)){
				$file[file_name] = $filename;
				$filename2 = is_utf8() ? iconv('gbk','utf-8',$filename) : $filename;
				$file[file_name2] = str_ireplace($rs[ftp_path],'<span class="txtblue">'.$rs[ftp_path].'</span>',$filename2);
				$ext = get_extension($filename);
				$arr = explode($rs[ftp_path],$filename2);
				$file[file_name_s] = $arr[1];
				$file[file_icon] = file_icon($ext);
				$file[file_path] = $rs[ftp_path];
				$file[file_size] = get_size(filesize($filename));
				$file[file_time] = date('Y-m-d H:i:s',filemtime($filename));
				$files[] = $file;
			}
		}
		$title = '文件入库 - 网盘FTP上传插件';
		require_once template_echo('import','','phpdisk_ftp');
	}
}
function sfilter($str){
	return str_ireplace(array(' ','(',')'),array('\ ','\(','\)'),$str);
}

?>