<?php 
/* 
 * ファイルアップロード処理
 */

App::import('Core', 'Shell');
App::import('Vendor', 'Media.MimeType');

class Upfile extends Object {

	/* Versionファイルの個別作成 */
	function make_version($previewVersion, $path, $options = array(), $overwrite = false)
	{
		if (empty($path) || empty($previewVersion)) {
			return null;
		}

		$Media = CorePlus::set_behavoir('Media.Media');

		// Confirgureの設定
		$name = Media::name($path);
		$filters = Configure::read('Media.filter.'. strtolower($name));
		if (empty($filters)) {
			return false;
		}
		if (!isset($filters[$previewVersion])) {
			return false;
		}
		$filter[$previewVersion] = $filters[$previewVersion];

		// mimeType設定
		if (isset($options['mime_type']) && !empty($options['mime_type'])) {
			if ($options['mime_type'] == 'original') {
				$orig_filepath = substr_replace($path, '', 0, strlen($previewVersion.'/'));

				$File = new File(MEDIA_TRANSFER. $orig_filepath);
				if (!$File->readable()) {
					return false;
				}
				$options['mime_type'] = MimeType::guessType($File->pwd());
			}
			$filter[$previewVersion]['convert'] = $options['mime_type'];
		}

		// Model設定
		if (!isset($options['model_name'])) {
			return null;
		}
		$Model = CorePlus::set_model($options['model_name']);

		// Versionファイル出力: ここから：MegiaBehavoir参考に
		$Media->setup($Model);
		$dir = substr_replace($path, '', strlen(basename($path)) * -1);
		$directory = Folder::slashTerm(MEDIA_FILTER . $dir);

		$Folder = new Folder($directory, true);
		if (!$Folder->pwd()) {
			$message  = "UpfileLib::make - Directory `{$directory}` ";
			$message .= "could not be created or is not writable. ";
			$message .= "Please check the permissions.";
			trigger_error($message, E_USER_WARNING);
			continue;
		}

		if (!$Medium = Medium::make(MEDIA_TRANSFER. $orig_filepath, $filter[$previewVersion])) {
			$message  = "UpfileLib::make - Failed to make version `{$previewVersion}` ";
			$message .= "of file `{$path}`. ";
			trigger_error($message, E_USER_WARNING);
			continue;
		}
		$maked_version = $Medium->store($directory . basename($orig_filepath), $overwrite);
		// Versionファイル出力: ここまで

		return $maked_version;
	}

}
