<?php
/**
 * @copyright ONE/DEPO Project
 * @license   PHP License 3.01 <http://www.php.net/license/3_01.txt>
 */

/**
 * PEAR::Cache
 * 
 * ※ インクルード・パスに存在する必要がある
 */
require_once 'Cache.php';

/**
 * 画像
 *
 * @package     imageview
 * @author      netnee T.Ototgawa <tomokauzu.otogawa@netnee.jp>
 * @access      public
 */
class Onedepo_Logic_Imageview {

    var $check_db = false;  // true or false


    var $image;

    var $code;
    var $subcode;
    var $div;
    var $size;
    var $sell;
    var $stock;

    var $cache_filepath;
    var $source_filename;
    var $source_format;



    /**
     * リクエストパラメータを取得
     * 
     * @access public
     * @param integer $code
     * @param integer $div
     * @param varchar $size
     */
    function set_parameters($code, $subcode, $div, $size, $sell, $stock)
    {
        $this->code    = $code;
        $this->subcode = $subcode;
        $this->div     = $div;
        $this->size    = $size;
        $this->sell    = $sell;
        $this->stock   = $stock;
    }


    /**
     * 画像を生成
     * 
     * @access public
     */
    function generate_img()
    {
        $log =& LogFactory::getLog();

        if (empty($this->code) || empty($this->div) || empty($this->size)) {
            $log->info("code error", "Onedepo_Logic_Imageview#generate_img");
            return false;
        }

        $this->set_source_filename();
        if (!is_file($this->source_filename)) {
            $log->info("nofile", "Onedepo_Logic_Imageview#generate_img");
            return false;
        }
        $this->set_cache_filename();

        if ($this->check_cache()) {
            return true;
        }

        $this->create_cache();
        return true;
    }

    function getFilename()
    {
        $div     = $this->div;
        $code    = $this->code;
        $subcode = $this->subcode;
        $size    = $this->size;
        $sell    = $this->sell;
        $stock   = $this->stock;

        $log =& LogFactory::getLog();

        $filename = "";
        // DBチェック
        //if ($this->check_db) {
        //    $list = $this->image->selectKey($div, $size, $code, $subcode, $sell, $stock);
        //} else {
            // ダミーデータ追加
            $list["generalcd"] = 1;
        //}

        if (!empty($list["generalcd"])) {
            $filename  = IMAGE_DIR ."/". $div ."/". $code;            
            $filename .= (!empty($subcode)) ? "-". $subcode : "";
            $filename .= $size . ".jpg";

            if ($div == 2) $filename = IMAGE_DIR ."/". $div ."/". $code. "-". $subcode. "-" . $sell . "-" . $stock . ".jpg"; 

            $log->debug($filename,"");
            if (is_file($filename)) {
                return $filename;
            } else {
                $filename = "";
            }
        }

        if (empty($filename)) {
            switch (strtolower($size)) {
                case "s":
                return IMAGE_S_NOTFOUND;
                break;

                case "m":
                return IMAGE_M_NOTFOUND;
                break;

                case "l":
                case "o":
                exit;
                break;
            }
        }
    }

    /**
     * 画像を出力
     * 
     * @access public
     */
    function output_img()
    {
        $log =& LogFactory::getLog();

        header('Pragma: public');
        header('Cache-Control: public');
        $this->send_content_type();
        $mt = filemtime($this->cache_fullpath);
        if ($mtime = filemtime($this->cache_fullpath)) {
            // Etag
            include_once 'Etag.php';
            $etag = new Etag($this->cache_fullpath.$mtime, $mtime);
            if ($etag->etagCheck()) {
                exit;
            }
        }

        @readfile($this->cache_fullpath);
        return true;
    }

    /**
     * @access protected
     */
    function create_cache()
    {
        $this->create_cache_subdir();

        $log =& LogFactory::getLog();
        if (copy($this->source_filename, $this->cache_fullpath)) {
            chmod($this->cache_fullpath, 0666);
            $log->debug("copy result = true", "Onedepo_Logic_Imageview#getFilename");
        } else {
            $log->debug("copy result = false", "Onedepo_Logic_Imageview#getFilename");
        }
    }


    /**
     * キャッシュ用サブディレクトリの作成
     * @access protected
     */
    function create_cache_subdir()
    {
        $log =& LogFactory::getLog();

        $subdir = dirname($this->cache_fullpath);
        if (!is_dir($subdir)) {
            // mkdir recursive
            $_dir = IMAGE_CACHEDIR;
            if (!is_dir($_dir) && !mkdir($_dir)) {
                $log->info("result = false", "Onedepo_Logic_Imageview#getFilename");
                return false;
            }
            $relative_path = substr($subdir, strlen(IMAGE_CACHEDIR)+1);
            $parts = explode('/', $relative_path);
            foreach ($parts as $part) {
                $_dir .=  '/' . $part;
                if (!is_dir($_dir) && !mkdir($_dir)) {
                    $log->info("result = false", "Onedepo_Logic_Imageview#getFilename");
                    return false;
                }
            }
        }
    }


    /**
     * ソースファイル名(拡張子からフォーマットも)設定
     * @access protected
     */
    function set_source_filename()
    {
        //ファイル名取得
        $this->source_filename = $this->getFilename();

        $pieces = explode('.', $this->source_filename);
        $this->source_format = $this->check_format(array_pop($pieces));
    }

    /**
     * send "Content-Type" header
     * php configure --enable-exif が必須
     * 
     * @access protected
     */
    function send_content_type()
    {
        $imagetype = exif_imagetype($this->source_filename);
        $mime_type = image_type_to_mime_type($imagetype);

        if (empty($mime_type)) {
            switch ($this->output_format) {
            case 'jpeg':
            case 'jpg':
            default:
                $mime_type = 'image/jpeg';
                break;
            case 'gif':
                $mime_type = 'image/gif';
                break;
            case 'png':
                $mime_type = 'image/png';
                break;
            }
        }

        header('Content-type: '. $mime_type);

    }

    /**
     * @access protected
     */
    function set_cache_filename()
    {
        $this->cache_fullpath =
                 IMAGE_CACHEDIR . '/' .
                 $this->div . '/' .
                 basename($this->source_filename);
    }

    /**
     * @access protected
     */
    function check_format($string)
    {
        switch (strtolower($string)) {
        case 'jpg' :
        case 'jpeg':
        default:
            return 'jpg';
        case 'gif':
            return 'gif';
        case 'png':
            return 'png';
        }
    }

    /**
     * キャッシュが残っているかどうかチェックする
     * 
     * @access protected
     * @return boolean
     */
    function check_cache()
    {
        return is_readable($this->cache_fullpath);
    }
     
}
?>