<?php
/**
 * Created by PhpStorm.
 * ftp的文件操作类
 * User: xiaoxie
 * Date: 2018/5/7
 * Time: 17:44
 **/

//namespace App\Tools;


class FtpFile
{
    static private $_instance=null;
     private $ftp = null;
     public $off;             // 返回操作状态(成功/失败)
     public $web;             // 返回操作状态(成功/失败)
     public $ls_msg;          // 返回消息

    //私有的构造方法
    public  function __construct($config){
        //实例化
       $this->conn_id = @ftp_connect($config['ftp_ip'],$config['ftp_port']) or die("FTP connection fail");
       //登录验证
       @ftp_login($this->conn_id,$config['ftp_username'],$config['ftp_password']);
       //是否开启被动模式
        if (isset($config['ftp_pasv']))
        {
            @ftp_pasv($this->conn_id,true);
        }
		$this->web=$config['ftp_ip'];
    }

    /**
     * Created by PhpStorm.
     * function: getInstance
     * Description:公有的静态方法
     * User: Xiaoxie
     * Email 736214763@qq.com
     * @return FtpFile|null
     *
     */
    static public function getInstance($config){
        if(!(self::$_instance instanceof self)){
            self::$_instance = new FtpFile($config);
        }
        return self::$_instance;
    }

    /**
     * Created by PhpStorm.
     * function: up_file
     * Description:上传文件
     * User: Xiaoxie
     * Email 736214763@qq.com
     * @param $path 本地路径
     * @param $newpath  若目标目录不存在则新建
     * @param bool $type
     *
     */
    function upafile($path,$newpath="",$type=false)
    {
		if($newpath=="")$newpath=$path;
        if($type) $this->dir_mkdirs($newpath);
        $this->off = @ftp_put($this->conn_id,$newpath,$path,FTP_BINARY);
		$ls_msg=date('Y-m-d H:i:s')." ".($path)." upload $newpath ".($this->off?"ok":"error");            
		$this->logs($path, $ls_msg,$this->web);
		
		return $ls_msg;

    }

    /**
     * Created by PhpStorm.
     * function: uploadFile
     * Description:多文件上传
     * User: Xiaoxie
     * Email 736214763@qq.com
     * @param array $files: local file => remote file
     * @param bool $type fold  
     */
    public function uploadFile($files,$type=false)
    {
        if (is_array($files))
        {
            foreach ($files as $key=>$file)
            {
                if($type)
                {
                    $this->dir_mkdirs($file);
                }
                $this->off = @ftp_put($this->conn_id,$file,$key,FTP_BINARY);
				$ls_msg=date('Y-m-d H:i:s')." ".($file )." upload ".($this->off?"ok":"error");
				
             }
        }else{
		         $this->off = @ftp_put($this->conn_id,$files,$files,FTP_BINARY);
				 $ls_msg=date('Y-m-d H:i:s')." ".($files )." upload ".($this->off?"ok":"error");
		}
		
		 $this->logs($files, $ls_msg,$this->web);
 
         return $ls_msg;
 
    }

    /**
     * Created by PhpStorm.
     * function: move_file
     * Description:移动文件 修改文件名
     * User: Xiaoxie
     * Email 736214763@qq.com
     * @param $path 原路径
     * @param $newpath 若目标目录不存在则新建
     * @param bool $type
     *
     */
    function move_file($path,$newpath,$type=true)
    {
        if($type) {
			$newpathfolder=substr($newpath,0,strrpos($newpath,"/"));
			$this->dir_mkdirs($newpathfolder);
		}
        $this->off = @ftp_rename($this->conn_id,$path,$newpath);
        if(!$this->off) {
            return "文件移动失败,请检查权限及原路径是否正确！";
        }else{
            return true;
        }
    }

    /**
     * Created by PhpStorm.
     * function: copy_file
     * Description:复制文件
     * User: Xiaoxie
     * Email 736214763@qq.com
     * @param $path原路径
     * @param $newpath 新路径
     * @param bool $type 若目标目录不存在则新建
     *
     */
    function copy_file($path,$newpath,$type=true)
    {
        $downpath = "/var/www/temp.txt";
        $this->off = @ftp_get($this->conn_id,$downpath,$path,FTP_BINARY);// 下载 
        if(!$this->off) 
        {
            return "文件复制失败,请检查权限及原路径是否正确！";
        }
        $this->up_file($downpath,$newpath,$type);
    }

    /**
     * Created by PhpStorm.
     * function: del_file
     * Description:删除文件
     * User: Xiaoxie
     * Email 736214763@qq.com
     * @param $path
     *
     */
    function del_file($path)
    {
        $this->off = @ftp_delete($this->conn_id,$path);
        if(!$this->off){
            return false;
        }
    }

    /**
     * Created by PhpStorm.
     * function: dir_mkdirs
     * Description:生成目录
     * User: Xiaoxie
     * Email 736214763@qq.com
     * @param $path 路径
     */
    function dir_mkdirs($path,$nofile=true)
    {
        $path_arr = explode('/',$path);       // 取目录数组 
       	if(!$nofile) $file_name = array_pop($path_arr);      // 弹出文件名
        $path_div = count($path_arr);        // 取层数 

        foreach($path_arr as $val)          // 创建目录 
        {
			//echo $val."+++";
            if(@ftp_chdir($this->conn_id,$val) == FALSE)
            {
				
                $tmp = @ftp_mkdir($this->conn_id,$val);
                if($tmp == FALSE)
                {
                    
                    exit;
                }
                @ftp_chdir($this->conn_id,$val);
            }
        }

        for($i=1;$i<=$path_div;$i++)         // 回退到根 
        {
            @ftp_cdup($this->conn_id);
        }
    }
    /**
     * 获取目录文件列表
     * @access  public
     * @param   string  目录标识(ftp)
     * @return  array
     */
    public function filelist($path) {
        if( ! $this->_isconn()) {
            return FALSE;
        }
        return @ftp_nlist($this->conn_id , $path);
    }


    /**
     * 目录改变
     * @access  public
     * @param   string  目录标识(ftp)
     * @param   boolean
     * @return  boolean
     */
    public function chgdir($path = '', $supress_debug = FALSE)
    {
        if ($path == '' OR !$this->_isconn()) {
            return FALSE;
        }
        $result = @ftp_chdir($this->conn_id , $path);
        if ($result === FALSE) {
            if ($this->debug === TRUE AND $supress_debug == FALSE) {
                $this->_error("ftp_unable_to_chgdir:dir[" . $path . "]");
            }
            return FALSE;
        }
        return @ftp_pwd($this->conn_id );
//        return TRUE;
    }
	
//查看文件日期
function getdate($file)
{ 
	   $buff = ftp_mdtm($this->conn_id, $file);
	  // 如果成功返回一个 UNIX 时间戳，否则返回 -1。
	  if ($buff != -1) {
		  // 输出 somefile.txt 最后的修改时间
		  return date ("Y-m-d H:i:s", $buff);
	  } else {
		  return false;
	  }
}

//查看文件时间戳
function gettimestamp($file)
{ 
	   $buff = ftp_mdtm($this->conn_id, $file);
	  // 如果成功返回一个 UNIX 时间戳，否则返回 -1。
	  if ($buff != -1) {
		  // 输出 somefile.txt 最后的修改时间
		  return   $buff;
	  } else {
		  return false;
	  }
}

//查看文件是否存在
    function iffileexists($filename)
    {
		//echo ftp_size($this->conn_id ,$filename)."==";
        if(ftp_size($this->conn_id ,$filename)==-1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    /**
     * 判断con_id ftp 是否连接
     *
     * @access  private
     * @return  boolean
     */
    private function _isconn() {
        if( ! is_resource( $this->conn_id )) {
            if($this->debug === TRUE) {
                $this->_error("ftp_no_connection");
            }
            return FALSE;
        }
        return TRUE;
    }

 

/*
------------------------------------------------------
参数：
$currentProgram   目前运行程序
$currentFunction 目前功能
$parameter  参数
程序功能：写入日志函数
------------------------------------------------------
*/

    public function logs($files,$info,$ip="",$username='admin',$oldfile="",$date="")
	{
	require_once('conn.php');
	global $logSpace,$logStat;
	if($logStat=='stop'){return;}
	$date=  date("Y-m-d H:i:s") ;
	
	
	$opendb=new mydb();
	require('char_set.php');
	
	
	$select_sql2="select * from ls_ftplog ";
	$select_query2=$opendb->query($select_sql2);
	$select_rows2=mysql_num_rows($select_query2); //总数
	
	
	$insert_sql="insert into ls_ftplog(date,files,info,oldfile,memo,ip,username) values ('".$date."','".$files."','" .$info."','".$oldfile."','".$memo."','".$ip."','".$username."')";
	//echo $insert_sql;
	$insert_query=$opendb->query($insert_sql);	
	}

    /**
     * Created by PhpStorm.
     * function: close
     * Description:关闭链接
     * User: Xiaoxie
     * Email 736214763@qq.com
     *
     */
    public function close()
    {
        @ftp_close($this->conn_id);
    }

    /**
     * 关闭链接
     *单例模式打开析构方法
     */
    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        //@ftp_close($this->conn_id);
    }


}