<?php
/*
	DevSaver web framework
	copyright (c) 2013-2016 DevSaver
		web:  www.devsaver.com
		mail: support@devsaver.com
		
*/

class CPlUpload {
	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function __construct($path = null) {

		if ($path === null) {
			$path = "../upload/tmp/";
		}
		
		$this->path = $path;
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Render($params) {
		global $_CONF;

		$template = new CTemplateDynamic("templates/forms.massupload.htm");

		return $template->blockReplace(
			"Main" , 
			array(
				"action"	=> $params["action"] , 
				"path"		=> $_CONF["url"] ,
				"skin"		=> $params["skin"]
			)
		);
	}
	


	public static function NewInstance($path = null) {
		return new self($path);
	}


	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function SetFunction($type , $data) {

		$this->functions[$type] = $data;

		return $this;
	}
	
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Run() {

		if (isset($_REQUEST["name"])) {
			$fileName = $_REQUEST["name"];
		} elseif (!empty($_FILES)) {
			$fileName = $_FILES["file"]["name"];
		} else {
			$fileName = uniqid("file_");
		}

		$filePath = $this->path . $fileName;

		// Chunking might be enabled
		$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
		$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


		StembaseErrorsHandlerDisable();

		// Open temp file
		if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
			die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
		}

		if (!empty($_FILES)) {
			if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
			}

			// Read binary input stream and append it to temp file
			if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		} else {	
			if (!$in = @fopen("php://input", "rb")) {
				die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
			}
		}



		while ($buff = fread($in, 4096)) {
			fwrite($out, $buff);
		}

		@fclose($out);
		@fclose($in);

		// Check if file has been uploaded
		if (!$chunks || $chunk == $chunks - 1) {
			// Strip the temp .part suffix off 
			rename("{$filePath}.part", $filePath);


			//save the image to the database and update the category			
			if ($this->functions["onComplete"])
				call_user_func($this->functions["onComplete"], $filePath , $fileName);
		}

		// Return Success JSON-RPC response
		die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');

		StembaseErrorsHandlerRestore();
	}
	
	
}


?>