<?php
class TImage {
	var $fp;
	function __construct($fp=NULL) {
		$this->fp = $fp;
	}

	function _listDir($parent) {
		$lists = glob($parent.'*');
		$ret = array();
		foreach ($lists as $l) {
			if ($l == '.' || $l == '..')
				continue;

			if (is_dir($l)) {
				$ret[basename($l)] = $this->_listDir($l.'/');
			}
		}
		return $ret;
	}

	function listDir() {
		return $this->_listDir(IMG);
	}

	function listImage($d) {
		$d = str_replace('.', '', $d);
		$lists = glob(IMG.$d.'/*');
		$ret = array();
		foreach ($lists as $l)
			if (is_file($l))
				$ret[] = basename($l);

		return $ret;
	}

	function check() {
		$ext = strtolower(pathinfo($this->fp['name'], PATHINFO_EXTENSION));
		$white_list = array('png', 'jpg', 'jpeg', 'gif');
		if (! in_array($ext, $white_list, TRUE))
			return FALSE;

		return TRUE;
	}

	function resize($dist, $target=NULL, $del=TRUE) {
		if (! $target)
			$target = $this->fp['tmp_name'];

		$image_info = getimagesize($target);
		if (! $image_info)
			return FALSE;

		$image = NULL;
		$image_type = $image_info[2];
		switch($image_type) {
			case IMAGETYPE_JPEG:
				$image = imagecreatefromjpeg($target);
			break;
			case IMAGETYPE_GIF:
				$image = imagecreatefromgif($target);
			break;
			case IMAGETYPE_PNG:
				$image = imagecreatefrompng($target);
			break;
		}
		if (empty($image))
			return FALSE;

		$w = imagesx($image);
		$h = imagesy($image);
		$new_w = $w;
		$new_h = $h;
		if (IMG_MAX_SIZE) {
			if ($w > $h) {
				if ($w > IMG_MAX_SIZE) {
					$new_h = $new_h * (IMG_MAX_SIZE / $w);
					$new_w = IMG_MAX_SIZE;
				}
			} else {
				if ($h > IMG_MAX_SIZE) {
					$new_w = $new_w * (IMG_MAX_SIZE / $h);
					$new_h = IMG_MAX_SIZE;
				}
			}
		}

		$new_image = imagecreatetruecolor($new_w, $new_h);
		imagecopyresampled(
			$new_image,
			$image,
			0,
			0,
			0,
			0,
			$new_w,
			$new_h,
			$w,
			$h
		);

		imagedestroy($image);

		switch($image_type) {
			case IMAGETYPE_JPEG:
				imagejpeg($new_image, $dist, IMG_JPEG_QUALITY);
			break;
			case IMAGETYPE_GIF:
				 imagegif($new_image, $dist);
			break;
			case IMAGETYPE_PNG:
				imagepng($new_image, $dist);
			break;
		}

		imagedestroy($new_image);

		if ($del)
			@unlink($target);

		return TRUE;
	}

	function save() {
		$p = $this->getImagePath($this->fp['tmp_name'], $this->fp['name']);
		if ($p === FALSE)
			return FALSE;

		//$ret = move_uploaded_file($this->fp['tmp_name'], IMG.$p);
		$ret = $this->resize(IMG.$p);
		if ($ret === FALSE)
			return FALSE;

		return $this->getUrl($p);
	}

	function getUrl($p) {
		if (substr(IMG_URL, 0, 4) != 'http') {
			$ssl = isset($_SERVER['HTTPS']);
			$default_port = $ssl ? '443' : '80';
			return ($ssl ? 'https' : 'http') . '://'. $_SERVER['SERVER_NAME']. ($_SERVER['SERVER_PORT'] == $default_port ? '' : ':'.$_SERVER['SERVER_PORT']).IMG_URL.$p;
		}
		return IMG_URL.$p;
	}

	function getImagePath() {
		$name = hash_visualization(md5(file_get_contents($this->fp['tmp_name']), TRUE), 0, 16);
		$ext = strtolower(pathinfo($this->fp['name'], PATHINFO_EXTENSION));

		$p = IMG;
		$dirs = array();
		for ($i=0; $i<IMG_DIR_COUNT; $i++) {
			$d = substr($name, $i, 1);
			$p .= $d.'/';
			if (! is_dir($p)) {
				$ret = @mkdir($p);
				if ($ret === FALSE)
					return FALSE;
			}
			$dirs[] = $d;
		}

		$name = substr($name, IMG_DIR_COUNT);

		$filepath = $p.$name.'.'.$ext;
		if (file_exists($filepath)) {
			$files = glob($p.$name.'*');
			$name .= count($files);
			if (file_exists($p.$name)) { // exception case
				return FALSE;
			}
		}

		return implode('/',$dirs).'/'.$name.'.'.$ext;
	}

	function delete($d, $with_posts = FALSE) {
		$sp = explode('/', $d);
		$secure_path = array();
		$secure_path[] = array_pop($sp);
		while($v = array_pop($sp)) {
			array_unshift($secure_path, str_replace('.', '', $v));
		}
		$path = IMG.implode('/', $secure_path);
		if (! is_file($path))
			return FALSE;

		$ret = @unlink($path);
		if ($ret === FALSE)
			return FALSE;
		$t = $this->getUrl($d);

		if ($with_posts) {
			//これでも消し切れないので省略（別URLに関連付けられている書き込みなどが結局は残る）
			/*
			include 'db.inc.php';
			$ids = $db->selectList('url_posts', 'id', 'url=?', array($t));
			if (! empty($ids)) {
				$str_ids = array(implode(',',$ids));
				$db->pureDelete('posts', 'id in(?)', $str_ids);
				$db->pureDelete('url_posts', 'id in(?)', $str_ids);
				$db->pureDelete('theme_posts', 'id in(?)', $str_ids);
				$db->pureDelete('keyword_posts', 'id in(?)', $str_ids);
			}
			*/
		}

		return TRUE;
	}
}
?>