<?php 

$path = $_GET['path'];
$size = isset($_GET['size'])?$_GET['size']:NULL;
define('BASEPATH', getcwd());
chdir('../../adminsavvy/');
chdir('/home/savvy/savvy/adminsavvy'); // DEBUG
require 'backend.php';
require 'application/libraries/Googlestorage.php';

$uniqueId = pathinfo($path, PATHINFO_FILENAME);
$objectName = pathinfo($path, PATHINFO_BASENAME);

$host = $savvyext->cfgReadChar('database.host');
$name = $savvyext->cfgReadChar('database.name');
$user = $savvyext->cfgReadChar('database.user');
$pass = $savvyext->cfgReadChar('database.pass');
$port = $savvyext->cfgReadLong('database.port');

$dbconn = pg_connect("host=${host} port=${port} dbname=${name} user=${user} password=${pass}");
if (!$dbconn) {
    // Show error
    showfile('errorspy.jpg');
}

$q = "select a.*,b.name as bucket from card_images a left join card_image_category b on (b.id=a.catid) where a.uniqueid = '".pg_escape_string($uniqueId)."'";
$r = pg_query($q);
if ($r && pg_num_rows($r) && $f=pg_fetch_assoc($r)) {
    $image = $f;
} else {
    // Show not found
    showFile('image_not_found.png');
}

$storage = new GoogleStorage();
$storage->Init(
    $savvyext->cfgReadChar('google.storage_project_id'),
    $savvyext->cfgReadChar('google.storage_auth_file')
);

try {
    $data = $storage->DownloadObject($image['bucket'],$objectName);
    header('Content-type: image/'.$image['format']);
    if ($size!=NULL && preg_match('/^([0-9]{2,4})x([0-9]{2,4})$/i', $size, $resize)==1 
            && count($resize)>2 && ((int)$resize[1])>0 && ((int)$resize[2])>0) {
        $temp_file = tempnam(sys_get_temp_dir(), $uniqueId);
        file_put_contents($temp_file, $data);
        require(BASEPATH.'/simple_image.php');
        $resized = new SimpleImage();
        $resized->load($temp_file);
        $resized->resize($resize[1], $resize[2]);
        $resized->output();
        unlink($temp_file);
    } else {
        echo $data;
    }
} catch (Exception $e) {
    showFile('error.png');
    /*
    foreach ($storage->ListBuckets()as $b) {
       echo $b->name()."<br>";
    }
    var_dump($storage->ListObjects($image['bucket']));
    */
}

function showFile($file,$path=BASEPATH) {
    header('Content-type: '.mime_content_type($path.'/'.$file));
    echo (file_get_contents($path.'/'.$file));
    exit();
}

/*
$file = 'feed1.jpg';
header('Content-type: '.mime_content_type($file));
echo (file_get_contents($file));
*/

pg_close($dbconn);
