<?php // vim:set et ts=4 sw=4 sts=4:
# Copyright (C) 2003-2014 hipplay Inc.
#
# This is UNPUBLISHED PROPRIETARY SOURCE CODE OF hipplay Inc.
# The copyright notice above does not evidence any actual or intended
# publication of such source code. The contents of this file may not
# be disclosed to third parties, copied or duplicated in any form, in
# whole or in part, without the prior written permission of
# hipplay Inc.
#


namespace HipPlayConnect\FileSystem;

/**
 * Utility functions for making thumbnail previews for image files
 */
class AxThumbnails {

    const DEBUG_THUMBS=TRUE;

    /* internal function: needThumbnail()
     * - checks if we need to make the given thumbnail
     */
    public static function needThumbnail( $image_file, $dest_file )
    {
        // dest file exists
        if ( is_array( $stat = @oeutil_stat( $dest_file ) ) )
        {
            /* If the thumbnail already exists, only generate it if it's
               corrupt or changed or if it's the same size as our old thumbnails and webviews */
            if
            (
                    $stat[ 7 ] != 0 &&
                    $stat[ 7 ] != 10362 && // old thumbnail size
                    $stat[ 7 ] != 11311 && // old thumbnail size
                    $stat[ 7 ] != 10410 && // old thumbnail size
                    $stat[ 7 ] != 31432 && // old webview   size
                    $stat[ 7 ] != 31560 && // old webview   size
                    $stat[ 7 ] != 25944 && // old webview   size
                    $stat[ 9 ] >= filemtime( $image_file )
            )
                return FALSE;
        }
        else
        {
            // dest file does not exist, need thumbnail, but first create dir if needed
            $tdir = AxFile::getDirname($dest_file);
            if(!file_exists( $tdir ))
                mkdir($tdir, 0777, TRUE);
        }

        // Guess we do need to make it
        return TRUE;
    }

    /* makeThumbnail()
     * - spawns off the thumbnail creation.  Returns TRUE if a recent thumbnail
     *   already exists, FALSE if it's making one
     */
    public static function makeThumbnail($image_file,$dest_file,$twidth, $theight)
    {
        if (self::DEBUG_THUMBS)
            error_log("Checking for cached thumbnail: $dest_file");
        if( !self::needThumbnail( $image_file,$dest_file ) ) {
            if (self::DEBUG_THUMBS)
                error_log("Thumbnail cached");
            return $dest_file;
        }

        if (self::DEBUG_THUMBS)
            error_log("Thumbnail not cached");

        // if something goes wrong (wrong permission on the file...), return failure
        $imageSize = @getimagesize( $image_file );
        if ( FALSE === $imageSize ) {
            error_log("Source could not be read.");
            return NULL;
        }

        list( $imageWidth, $imageHeight ) = $imageSize;

        if (self::DEBUG_THUMBS)
            error_log("Image size: $imageWidth x $imageHeight");

        // if the thumbnail is larger than the image, use the image size
        if ( $twidth >= $imageWidth && $theight >= $imageHeight ) {
            $theight = $imageHeight;
            $twidth  = $imageWidth;
        }

        // otherwise scale
        else {
            $thumbScale = $twidth / $theight;
            $imageScale = $imageWidth / $imageHeight;
            if ( $thumbScale > $imageScale )
                $twidth  = floor( $theight * $imageScale );
            else
                $theight = floor( $twidth / $imageScale );
        }

        //
        // simply copy the file if it's smaller than what we need
        //
        if( $imageWidth <= $twidth && $imageHeight <= $theight )
            copy( $image_file, $dest_file );

        else
        {
            $tmpfname = tempnam( "/tmp", "ThumbnailImages-" );

            $image_suffix = substr($image_file, -5);
            if (0 != stripos($image_suffix, ".jpeg") &&
                1 != stripos($image_suffix, ".jpg")) {
                error_log("$image_file is not a *.jpeg or *.jpg");
                return FALSE;
            }

            $image_file_escaped = str_replace("'", "'\"'\"'", $image_file);

            if (self::DEBUG_THUMBS)
                error_log("Escaped filename: " . print_r($image_file_escaped, TRUE));

            $command = implode(" ", array(
                    "/usr/bin/epeg",
                    '-w', $twidth,
                    '-h', $theight,
                    "'" . $image_file_escaped . "'",
                    $tmpfname,
                    ">", "/tmp/thumbnail.log", "2>&1"
            ));

            if (self::DEBUG_THUMBS)
                error_log("Thumbnail command: " . $command);

            $result = system($command, $retval);

            if (self::DEBUG_THUMBS) {
                error_log("Result: $result");
                error_log("Return Value: $retval");
            }

            if (self::needThumbnail($image_file, $tmpfname)) {
                if (self::DEBUG_THUMBS)
                    error_log("Failed to create thumbnail.");
                return FALSE;
            }

            if (!copy( $tmpfname, $dest_file )) {
                if (self::DEBUG_THUMBS)
                    error_log("Could not copy to destination.");
                rename($tmpfname, $tmpfname . ".jpg");
                return $tmpfname . ".jpg";
            }

            if (self::needThumbnail($image_file, $dest_file)) {
                if (self::DEBUG_THUMBS)
                    error_log("Unsuccessful thumbnailing.");
                rename($tmpfname, $tmpfname . ".jpg");
                return $tmpfname . ".jpg";
            }

            unlink( $tmpfname );

            if (self::DEBUG_THUMBS)
                error_log("Successful thumbnailing: $dest_file");
        }

        self::changeFileOwner( $dest_file );
        return $dest_file;
    }

    // TODO: setowner?
    private static function changeFileOwner( $FilePath, $Restrict = false, $Recurse = false )
    {
        $FilePath = realpath( $FilePath );

        $dirs = explode( '/', $FilePath );
        $GroupName =
                count( $dirs ) > 3 &&
                $dirs[ 1 ] == 'home' &&
                $dirs[ 2 ] != '0common' &&
                $dirs[ 2 ] != '0external' &&
                $dirs[ 2 ] != '0albums'
                        ? $dirs[ 2 ]
                        : 'apache';

        $command = array(
                '/usr/bin/setowner',
                escapeshellarg($FilePath),
                escapeshellarg($GroupName),
                $Restrict ? 'restrict'  : '',
                $Recurse  ? 'recursive' : '',
        );

        exec( implode(" ", $command) );

        return( TRUE );
    }

}
