<?

namespace platyFramework;

/*
 * ptyFormUploadManager
 *
 * 폼 파일 관리자
 *
*/

class ptyFormFileManager
{
	var $tableName;
	var $storeDir;
	var $storeUrl;

	function __construct($tableName = "t_files")
	{
		GLOBAL $platyFramework;
		$this->db = $platyFramework->db;
		$this->tableName = $tableName;
		$this->setStoreDir(PLATYFRAMEWORK_DATADIR . "/files");
		$this->setStoreUrl(PLATYFRAMEWORK_DATAURL . "/files");
		$this->_checkTableExistsAndCreate();
	}

	static function build($tableName = "t_files")
	{
		$class = new static($tableName);
		return $class;
	}

	function create($tableName = "t_files")
	{
		$tmp = new ptyFormFileManager($tableName);
		return $tmp;
	}

	public function __toString()
	{
		return "ptyFormFileManager";
	}

	function _checkTableExistsAndCreate()
	{
		if ($this->db->sql_result("SHOW TABLES LIKE '$this->tableName'"))
			return;

		$this->db->sql_query("
			CREATE TABLE IF NOT EXISTS `$this->tableName` (
			`id` int(11) NOT NULL AUTO_INCREMENT,
			`regDateTime` datetime,
			`ip` varchar(64) CHARACTER SET utf8 NOT NULL DEFAULT '',
			`enabled`	tinyint(1) DEFAULT 0,
			`uploadFileName` varchar(256) CHARACTER SET utf8 NOT NULL DEFAULT '',
			`storedFileName` varchar(256) CHARACTER SET utf8 NOT NULL DEFAULT '',
		    `fileSize` varchar(256) CHARACTER SET utf8 NOT NULL DEFAULT '',
			`fileType` varchar(256) CHARACTER SET utf8 NOT NULL DEFAULT '',
			
			`userKey1` varchar(256),
			`userKey2` varchar(256),
			
			PRIMARY KEY (`id`)
		) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
		");
	}

	function setStoreDir($dir)
	{
		$this->storeDir = $dir;
		return $this;
	}

	function setStoreUrl($dir)
	{
		$this->storeUrl = $dir;
		return $this;
	}

	function setOnFinish($onFinish)
	{
		$this->onFinish = $onFinish;
		return $this;
	}

	function uploadAll($key1, $key2, $files, $deletes)
	{
//		ptyDebug($_SESSION);
		// ptyDebug($files);
		// ptyDebug($deletes);
		foreach ($files as $key => $v) {
			foreach ($v as $inputName => $values) {
				$i = 0;
				foreach ($values as $value) {
					$out[$inputName][$i][$key] = $value;
					$i++;
				}
			}
		}

		// 삭제 처리
		foreach ($deletes as $id)
		{
			$fetch = $this->db->clear()->addSelect("*")->addFrom($this->tableName)->addWhereEqual("id", "$id")->sql_fetch();

			if ($fetch['id'])
			{
				$fileName = sprintf("%s/%s/%s", $this->storeDir, $key1, $fetch[storedFileName]);
				unlink($fileName);
				$this->db->clear()->addSelect("*")->addFrom($this->tableName)->addWhereEqual("id", "$id")->delete();
			}
		}

		foreach ($out as $name => $values) {
//			ptyDebug("name = ".print_r($name, true));
			foreach ($values as $index => $info) {
//				ptyDebug("index = ".print_r($index, true));
//				ptyDebug("info = ".print_r($info, true));

				if ($info['error'] != UPLOAD_ERR_OK)
					continue;

				$desired_storedDir = $this->storeDir;
				if (is_dir($desired_storedDir) == false) {
					mkdir("$desired_storedDir", 0755, true);        // Create directory if it does not exist
				}

				$pi = pathinfo($info[name]);
//				ptyDebug("info = " . print_r($info, true));
//				ptyDebug("pi = " . print_r($pi, true));

				if (stristr($pi['extension'], "html") ||
					stristr($pi['extension'], "htm") ||
					stristr($pi['extension'], "php") ||
					stristr($pi['extension'], "inc")
				) {
					continue;
				}

				$dir = sprintf("%s/%s", $this->storeDir, $key1);
				mkdir($dir, 0755, true);
//				ptyDebug("dir = " . $dir);
				$outFileName = sprintf("%s/%s/%s_%s_%s_%d.%s", $this->storeDir, $key1, $name, $key2, $index, time(), $pi['extension']);
				$dbFileName = sprintf("%s_%s_%s_%d.%s", $name, $key2, $index, time(), $pi['extension']);

				// $cnt = $this->db->addWhere("")
				$set = array();
				$set[regDateTime] = "NOW()";
				$set[ip] = $_SERVER['REMOTE_ADDR'];
				$set[enabled] = 1;
				$set[uploadFileName] = $info[name];
				$set[storedFileName] = $dbFileName;
				$set[fileSize] = $info[size];
				$set[fileType] = $info[type];
				$set[userKey1] = $key1;
				$set[userKey2] = $key2;
				$set[userKey3] = $name;
				$set[position] = $index;

				$storedFileName = $this->db->clear()
					->addFrom($this->tableName)
					->addSelect("storedFileName")
					->addWhereEqual("position", $index)
					->addWhereEqual("userKey1", $key1)
					->addWhereEqual("userKey2", $key2)
					->addWhereEqual("userKey3", $name)
					->sql_result();

				// insert
				if (!$storedFileName) {
					move_uploaded_file($info[tmp_name], $outFileName);
					$this->db->clear()->addFrom($this->tableName)->addSet($set)->insert();
				} // update
				else {
					$this->db->clear()
						->addFrom($this->tableName)
						->addSet($set)
						->addWhereEqual("position", $index)
						->addWhereEqual("userKey1", $key1)
						->addWhereEqual("userKey2", $key2)
						->addWhereEqual("userKey3", $name)
						->update();

					$beforeFileName = sprintf("%s/%s/%s", $this->storeDir, $key1, $storedFileName);
					unlink($beforeFileName);
					move_uploaded_file($info[tmp_name], $outFileName);
				}
			}
		}
	}

	function getUrl($userKey1, $userKey2, $userKey3, $position = 0, &$fileId = 0)
	{
		// $this->db->setDebug(1);
		$row = $this->db->clear()
			->addFrom($this->tableName)
			->addSelect("id, storedFileName")
			->addWhereEqual("userKey1", $userKey1)
			->addWhereEqual("userKey2", $userKey2)
			->addWhereEqual("userKey3", $userKey3)
			->addWhereEqual("position", $position)
			->addOrderBy("position")
			->sql_fetch();

		/*
		$fileName = $this->db->sql_result("select storedFileName FROM $this->tableName WHERE id = '$id' AND enabled = 1");
		*/

		$fileName = $row['storedFileName'];
		$fileId = $row['id'];

		if ($fileName)
			return $this->storeUrl . "/$userKey1/$fileName";
		else
			return "";
	}


	function upload()
	{
		$formParent = $this->formParent;
		$formName = $this->formName;
		$errors = array();

		foreach ($_FILES[$formParent]['tmp_name'] as $arrayKeyName => $tmp_name) {
			if ($arrayKeyName != $formName)
				continue;

			$file_size = $_FILES[$formParent]['size'][$formName];
			$file_tmp = $_FILES[$formParent]['tmp_name'][$formName];
			$file_type = $_FILES[$formParent]['type'][$formName];
			$ext = pathinfo($_FILES[$formParent]['name'][$formName], PATHINFO_EXTENSION);
			$file_name = base64_encode($name) . "_" . $value . "." . $ext;

			if ($file_size > 20971520) {
				$errors[] = 'File size must be less than 20 MB';
				cpbDebug($errors);
			}

			if ($file_size < 1) {
				// echo "filesize error. file size = $file_size <Br>";
				continue;
			}


			$query = "INSERT into $this->tableName (`regDateTime`, `ip`, `uploadFileName`, `storedFileName`, `fileSize`, `fileType`, `userData`, `enabled`) VALUES(
				NOW(),
				'$_SERVER[REMOTE_ADDR]', 
				'" . $_FILES[$formParent][name][$formName] . "',
				'$file_name',
				'$file_size','$file_type', '$userData', 1)";

			$this->db->query($query);
			$id = mysql_insert_id();
			$file_name = $id . "_" . uniqid() . ".$ext";

			$desired_storedDir = $this->storeDir;

			if (empty($errors) == true) {
				if (is_dir($desired_storedDir) == false) {
					mkdir("$desired_storedDir", 0700);        // Create directory if it does not exist
				}

				if (is_dir("$desired_storedDir/" . $file_name) == false) {
					move_uploaded_file($file_tmp, "$desired_storedDir/" . $file_name);
				} else {
					//rename the file if another one exist
					$new_storedDir = "user_data/" . $file_name . time();
					rename($file_tmp, $new_storedDir);
				}

				if ($this->onFinish) {
					$func = $this->onFinish;
					$func($this, $id);
				}

				$this->db->sql_query("UPDATE $this->tableName SET storedFileName = '$file_name' WHERE id = '$id'");
				return $id;
			} else {
				print_r($errors);
				exit;
			}
		}
	}

	function upload_old($filesName, $userId, $id, $userKey = "", $userData = "")
	{
		/*
		$userId = $this->user->getId();

		if (!$userId)
		{
			echo "userId is null";
			return false;
		}
		*/
		if (isset($_FILES[$filesName])) {
			$errors = array();

			foreach ($_FILES[$filesName]['tmp_name'] as $key => $tmp_name) {
				$file_name = uniqid() . "_" . $_FILES[$filesName]['name'][$key];
				$file_size = $_FILES[$filesName]['size'][$key];
				$file_tmp = $_FILES[$filesName]['tmp_name'][$key];
				$file_type = $_FILES[$filesName]['type'][$key];
				if ($file_size > 20971520) {
					$errors[] = 'File size must be less than 20 MB';
				}

				if ($file_size < 1) {
					// echo "$file_size < 1 <br>";
					continue;
				}

				$query = "INSERT into $this->tableName (`regDateTime`, `ip`, `userId`,`fileName`,`fileSize`,`fileType`, `id`, `userKey`, `userData`, `enabled`) VALUES(
					NOW(), '$_SERVER[REMOTE_ADDR]', '$userId','$file_name','$file_size','$file_type', '$id', '$userKey', '$userData', 1); ";

				$desired_storedDir = $this->storeDir;
				if (empty($errors) == true) {
					if (is_storedDir($desired_storedDir) == false) {
						mkdir("$desired_storedDir", 0700);        // Create directory if it does not exist
					}

					if (is_storedDir("$desired_storedDir/" . $file_name) == false) {
						move_uploaded_file($file_tmp, "$desired_storedDir/" . $file_name);
					} else {                                    //rename the file if another one exist
						$new_storedDir = "user_data/" . $file_name . time();
						rename($file_tmp, $new_storedDir);
					}
					$this->db->query($query);
				} else {
					print_r($errors);
					exit;
				}
			}

			return empty($error) ? true : false;
		}
	}


	static function copyRow($table, $id)
	{
		GLOBAL $db;
		$cols = $db->lst("SHOW COLUMNS FROM $table");
		$a = array();
		foreach ($cols as $col) {
			if ($col["Key"] == "PRI") {
				$primaryKey = $col[Field];
			} else {
				$a[] = $col[Field];
			}
		}

		$row = $db->fetch("SELECT `" . implode("`, `", $a) . "` FROM $table WHERE $primaryKey = '$id'");
		$q = $db->getKeyValues($row);
		$db->query("INSERT INTO $table SET $q");
		$lastId = mysql_insert_id();

		return $lastId;
	}


	function duplicate($id)
	{
		$newId = $this->copyRow($this->tableName, $id);
		$row = $this->db->fetch("SELECT * FROM $this->tableName WHERE id = '$newId'");

		$src = $this->storeDir . "/$row[storedFileName]";
		$storedFilePathInfo = pathinfo($src);

		$newFileName = uniqid($newId);
		$newFileName = $newId . "_" . "$newFileName." . $storedFilePathInfo[extension];

		$dst = $this->storeDir . "/$newFileName";
		$this->db->query("UPDATE $this->tableName SET regDateTime = NOW(), storedFileName = '$newFileName' WHERE id = '$newId'");
		copy($src, $dst);
		return $newId;
	}

	function get($id, $userKey = "")
	{
		$lst = $this->db->sql_list("SELECT * FROM $this->tableName WHERE enabled = 1 AND id = '$id' AND userKey = '$userKey'");

		$ret = array();
		foreach ($lst as $k => $v) {
			$ret[] = new cpbFileUploadImageItem($this, $id, $v);
		}
		return $ret;
	}

	function getFromUserIdAndId($userId, $id, $userKey)
	{
		$lst = $this->db->sql_list("SELECT * FROM $this->tableName WHERE enabled = 1 AND userId = '$userId' AND id = '$id' AND userKey = '$userKey'");

		$ret = array();
		foreach ($lst as $k => $v) {
			$ret[] = new cpbFileUploadImageItem($this, $id, $v);
		}
		return $ret;
	}


	function remove($id = "")
	{
		if (!$id)
			$id = $this->id;

		$this->db->sql_query("UPDATE $this->tableName SET enabled = 0 WHERE id = '$id' AND enabled = 1");
	}

	function delete($id)
	{
		if (!$id)
			$id = $this->id;

		$row = $this->db->sql_fetch("SELECT * FROM $this->tableName WHERE id = '$id'");
		$fileName = $this->storeDir . "/$row[storedFileName]";
		unlink($fileName);

		$this->db->query("DELETE FROM $this->tableName WHERE id = '$id'");
		return 0;
	}

	function modify($id)
	{
		$formParent = $this->formParent;
		$formName = $this->formName;
		$errors = array();

		foreach ($_FILES[$formParent]['tmp_name'] as $arrayKeyName => $tmp_name) {
			if ($arrayKeyName != $formName)
				continue;

			$file_size = $_FILES[$formParent]['size'][$formName];
			$file_tmp = $_FILES[$formParent]['tmp_name'][$formName];
			$file_type = $_FILES[$formParent]['type'][$formName];
			$upFileName = $_FILES[$formParent][name][$formName];
			$ext = pathinfo($_FILES[$formParent]['name'][$formName], PATHINFO_EXTENSION);

			if ($file_size > 20971520) {
				$errors[] = 'File size must be less than 20 MB';
				cpbDebug($errors);
			}

			if ($file_size < 1) {
				// echo "filesize error. file size = $file_size <Br>";
				continue;
			}

			$a = array();
			$a[ip] = $_SERVER[REMOTE_ADDR];
			$a[uploadFileName] = $upFileName;
			$a[fileSize] = $file_size;
			$a[fileType] = $file_type;
			$a[userData] = $userData;
			$a[enabled] = 1;

			if ((int)$id != 0)
				$item = $this->db->sql_fetch("SELECT id, storedFileName FROM $this->tableName WHERE id = '$id'");

			if ((int)$item[id] > 0) {
				$removeFileName = $this->storeDir . "/$item[storedFileName]";
				unlink($removeFileName);

				$file_name = $id . "_" . uniqid() . ".$ext";
				$a[storedFileName] = $file_name;
				$q = $this->db->getKeyValues($a);

				$this->db->query("UPDATE $this->tableName SET regDateTime = GETDATE(), $q WHERE id = '$id'");
			} else {
				$a[regDateTime] = "~NOW()";
				$this->db->addFrom($this->tableName)->insert($a);
				// $q = $this->db->getKeyValues($a);
				// $this->db->query("INSERT INTO $this->tableName SET regDateTime = NOW(), $q");

				//
				$id = mysql_insert_id();
				$file_name = $id . "_" . uniqid() . ".$ext";
				$a[storedFileName] = $file_name;
				$q = $this->db->getKeyValues($a);

				$this->db->query("UPDATE $this->tableName SET $q WHERE id = '$id'");
			}

			$desired_storedDir = $this->storeDir;
			if (empty($errors) == true) {

				if (is_dir($desired_storedDir) == false) {
					mkdir("$desired_storedDir", 0700);        // Create directory if it does not exist
				}

				if (is_dir("$desired_storedDir/" . $file_name) == false) {
					move_uploaded_file($file_tmp, "$desired_storedDir/" . $file_name);
				}
				/*
				else
				{
					//rename the file if another one exist
					$new_storedDir="user_data/".$file_name.time();
					rename($file_tmp,$new_storedDir) ;
				}
				*/

				if ($this->onFinish) {
					$func = $this->onFinish;
					$func($this, $id);
				}

				$this->db->sql_query("UPDATE $this->tableName SET storedFileName = '$file_name' WHERE id = '$id'");
				return $id;
			} else {
				print_r($errors);
				exit;
			}
		}
		return $id;
	}


}

class    cpbFileUploadImageItem
{
	var $parent;
	var $id;
	var $item;

	function __construct($parent, $id, $item)
	{
		$this->parent = $parent;
		$this->id = $id;
		$this->item = $item;
	}

	function getUrl()
	{
		$url = sprintf("http://%s/%s/%s", $_SERVER[HTTP_HOST], $this->parent->storedDir, $this->item[fileName]);
		return $url;
	}
}

?>
