<?php

/**
 * @name		CodeIgniter Advanced Images
 * @author		Jens Segers
 * @link		http://www.jenssegers.be
 * @license		MIT License Copyright (c) 2012 Jens Segers
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Media extends CI_Controller {

    public function resize($path = null, $file = null) {
        if (!$path || !$file) {
            redirect('Media/static/not_found-large.png');
        }
        $thumbs = ($path == 'static') ? IMAGES_STATIC : IMAGES;
        $thumbs .= DIRECTORY_SEPARATOR . '_thumbs' . DIRECTORY_SEPARATOR . $file;
        $pathinfo = pathinfo($thumbs . DIRECTORY_SEPARATOR . $file);
        $parts = explode("-", $pathinfo["filename"]);
        $size = end($parts);
        $original = dirname(dirname($thumbs)) . DIRECTORY_SEPARATOR . str_ireplace("-" . $size, "", $pathinfo["basename"]);

        $result = $this->_verify_image($size, $thumbs);
        if (!is_file($original) || $result['allowed'] == false) {
            if ($size == 'original') {
                $this->_render($original);
                return;
            }
            redirect('Media/static/not_found-' . $size . '.png');
        }
        if (!is_file($result['thumbs'])) {
            $this->_generate_thumbs($result['width'], $result['height'], $original, $result['thumbs']);
        }
        $this->_render($result['thumbs']);
    }

    private function _verify_image($size, $thumbs) {
        $this->load->config("images");
        $sizes = $this->config->item("image_sizes");
        $allowed = false;
        if (stripos($size, "x") !== false) {
            @list($width, $height) = explode("x", $size);
            foreach ($sizes as $s) {
                if ($width == $s[0] && $height == $s[1]) {
                    $allowed = true;
                    break;
                }
            }
        } else if (isset($sizes[$size])) {
            @list($width, $height) = $sizes[$size];
            $allowed = true;
            $thumbs = str_ireplace($size, $width . "x" . $height, $thumbs);
        }
        return array(
            'allowed' => $allowed,
            'thumbs' => $thumbs,
            'width' => isset($width) ? $width : null,
            'height' => isset($height) ? $height : null
        );
    }

    private function _generate_thumbs($width, $height, $original, $path) {
        $output = $original;
        if ($width >= 0 && $height >= 0) {
            // initialize library
            $config["source_image"] = $original;
            $config['new_image'] = $path;
            $config["width"] = $width;
            $config["height"] = $height;
            $config["dynamic_output"] = FALSE; // always save as cache

            $this->load->library('image_lib');
            $this->image_lib->initialize($config);

            $this->image_lib->fit();
            // check if the resulting image exists, else show the original
            if (file_exists($path)) {
                $output = $path;
            }
        }
        return $output;
    }

    private function _render($output) {
        $info = getimagesize($output);

        // output the image
        header("Content-Disposition: filename={$output};");
        header("Content-Type: {$info["mime"]}");
        header('Content-Transfer-Encoding: binary');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');

        @readfile($output);

//        echo file_get_contents($output);
    }

}
