<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 14-6-26
 * Time: 下午7:46
 * To change this template use File | Settings | File Templates.
 */
require_once ('config.php');

$strServer = "dhl-sftp01.rze.deutschepost.de";
$strServerPort = "22";
$strServerUsername = "CRG";
$strServerPassword = "Liit0kei";

$resConnection = ssh2_connect($strServer, $strServerPort);
if(!$resConnection) die("Unable connect sftp on ".date("Y-m-d H:i:s")."\n");
$condition = array(
    'fmt_code'=>"CRG",
    'fml_status'=>'0',
    'fmt_type'=>'EFILE',
);
$count = Service_FtpMessageSendlist::getByCondition($condition,"count(*)");
$pageSize = 20;
$totalPage = ceil($count/$pageSize);

if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
    for($page=1;$page<=$totalPage;$page++){
        $sendMessageList = Service_FtpMessageSendlist::getByCondition($condition,"*",$pageSize,$page,'fml_id desc');
        foreach($sendMessageList as $key=>$value){
            $resSFTP = ssh2_sftp($resConnection);

            $opts = array(
                'http'=>array(
                    'method'=>"GET",
                    'timeout'=>120,
                )
            );
            $context = stream_context_create($opts);
            $fileName = $value['fml_path'];
            $source_file =  APPLICATION_PATH . '/../data/Efile2015/'.$fileName;
            if(file_exists($source_file)){
                if(!copy($source_file,"ssh2.sftp://{$resSFTP}/CRG/".$fileName)) {
                    echo $fileName.' upload failed</br>';
                }else{
                    $updateSML = array(
                        'fml_status'=>'1',
                        'fml_update_time'=>date("Y-m-d H:i:s"),
                        'fml_send_time'=>date("Y-m-d H:i:s"),
                    );
                    Service_FtpMessageSendlist::update($updateSML,$value['fml_id'],'fml_id');
                    echo $fileName." upload file Success on ".date("Y-m-d H:i:s")."\n";
                }
            }else{
                echo "file ".$fileName." does't exist! ".date("Y-m-d H:i:s")."\n";
            }
        }
    }
}else{
    echo "Unable to authenticate on server on ".date("Y-m-d H:i:s")."\n";
}

