<?php
/****************************
 * File : awsfileserver.php
 * Author : Cygnusa
 * @2018
****************************/

//SECURITY 
if ( ! defined('APPLICATION_PATH')) exit('No direct script access allowed');

//AMAZON S3
require (dirname(__FILE__).'/../awsapi/aws-autoloader.php');
use Aws\S3\S3Client;
use Aws\Exception\AwsException;


//CLASS DEFINE
class awsfileserver
{
	//FUNCTION LISTS
	
	function __construct($parent)
	{
		//return connectS3();
	}
	
	/* ////////////////////////////////////// S3 CONNECT ///////////////////////////////// */	
	public static function connectS3()
	{
		//S3 CONNECTION
		$s3 = S3Client::factory(array(    
			'version' => 'latest',
			'region' => S3_REGION,
			'credentials' => array(
				'key' =>S3_ACCESSKEY,
				'secret' =>S3_SECRET_ACCESS
			)	
		));
		return $s3;
	}
    /* ///////////////////////////////////////////////////////////////////////////////////// */	
    
	/* ////////////////////////////////////// S3 URL ///////////////////////////////// */	
	public static function getS3Url($s3,$bucket,$obj)
	{
		$presignedUrl='';
		if(is_object($obj))
		{
			$cmd = $s3->getCommand('GetObject', [
					'Bucket' =>$bucket,
					'Key'    => $obj->key_name
			]);
			$request = $s3->createPresignedRequest($cmd, '+7200 minutes');
			$presignedUrl = (string) $request->getUri();
		}
		return $presignedUrl;
	}
    /* ///////////////////////////////////////////////////////////////////////////////////// */	
    
    /* ////////////////////////////////////// S3 URL ///////////////////////////////// */	
	public static function getS3FileUrl($s3,$bucket,$key_name)
	{
		$presignedUrl='';
		if(isset($key_name) && $key_name!='')
		{
			$cmd = $s3->getCommand('GetObject', [
					'Bucket' =>$bucket,
					'Key'    => $key_name
			]);
			$request = $s3->createPresignedRequest($cmd, '+7200 minutes');
			$presignedUrl = (string) $request->getUri();
		}
		return $presignedUrl;
	}
    /* ///////////////////////////////////////////////////////////////////////////////////// */	
    
	
	/* /////////////////////////////////   EXIST  ///////////////////////////////////// */	
	public static function checkexist($s3,$bucket,$obj)
	{
		$info = $s3->doesObjectExist($bucket,$obj->key_name);
		return $info;
	}
    /* ///////////////////////////////////////////////////////////////////////////////////// */	
    
	/* /////////////////////////////////  UPLOAD   /////////////////////////////////// */	
	public static function checkupload($parent,$s3,$bucket,$upload_key,$s3upload_key)
	{
		//$keyfile_name="uploads/noimage.jpg";
	 
		try {
				 
			$params = array(
				'Bucket' =>$bucket,
				'Key'    =>$upload_key,
				'SourceFile'   =>$s3upload_key
			);		

			// Using commands explicitly.
			$command = $s3->getCommand('PutObject', $params); 
			$result = $s3->execute($command); 
			

		} catch (AwsException $e) {
			// output error message if fails
			//echo $e->getMessage();
			$parent->response(array('response'=>'failed','message'=>'S3 SERVER ERROR'),500);
		}
	}	
	/* ////////////////////////////////////////////////////////////////////////////// */
	
    /* /////////////////////////////////  DELETE   /////////////////////////////////// */	
	public static function deleteobject($parent,$s3,$bucket,$s3upload_key)
	{
		//$keyfile_name="uploads/noimage.jpg";
	 	try {
				 
			
			$result = $s3->deleteObject(array(
				'Bucket' => $bucket,
				'Key'    => $s3upload_key
			));   
		
			 
			return true;
			
		} catch (AwsException $e) {
			// output error message if fails
			//echo $e->getMessage();
			$parent->response(array('response'=>'failed','message'=>'S3 SERVER ERROR'),500);
		}
	}
    /* ////////////////////////////////////////////////////////////////////////////// */
    
    /* /////////////////////////////////  MOVE TO SE TO LOCAL   /////////////////////////////////// */	
	public static function movefiletolocal($parent,$s3,$bucket,$data)
	{
		//data
	 	try {
			//$data=array(["s3"=>"s3 path","local"=>"local path"],["s3 path","local"=>"local path"],....));
            //$arr=[];
            if(is_array($data) && count($data)>0)
            {
                foreach($data as $val)
                {
                    if(!(is_array($val) && array_key_exists("s3",$val) && array_key_exists("local",$val)))  $parent->response(array('response'=>'failed','message'=>'INVALID DATA IN - awsfiledsever.php "movefiletolocal"'),500);
                    
                    $object = $s3->getObject(['Bucket' => $bucket, 'Key' => $val["s3"],'SaveAs'=>$val["local"]]);
                }
                //print_r($arr);
             
            }else
            {
                $parent->response(array('response'=>'failed','message'=>'INVALID DATA IN - awsfiledsever.php "movefiletolocal"'),500);
            }
			 
		} catch (AwsException $e) {
			// output error message if fails
			//echo $e->getMessage();
			$parent->response(array('response'=>'failed','message'=>'S3 SERVER ERROR'),500);
		}
	}
    /* ////////////////////////////////////////////////////////////////////////////// */
    
    
}

?>