<?php
/*
 * $RCSfile: GalleryDerivativeImage.class,v $
 *
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2005 Bharat Mediratta
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA  02110-1301, USA.
 */
/**
 * @version $Revision: 1.47 $ $Date: 2005/08/23 03:49:02 $
 * @package GalleryCore
 * @author Bharat Mediratta <bharat@menalto.com>
 */

/**
 * Load the parent class
 */
GalleryCoreApi::relativeRequireOnce('modules/core/classes/GalleryDerivative.class');

/**
 * A DataContainer for images
 *
 * A container for a single image.  This image may or may not be
 * cacheable (depending on whether or not it's a derivative image).
 *
 * @g2 <class-name>GalleryDerivativeImage</class-name>
 * @g2 <parent-class-name>GalleryDerivative</parent-class-name>
 * @g2 <schema>
 * @g2   <schema-major>1</schema-major>
 * @g2   <schema-minor>0</schema-minor>
 * @g2 </schema>
 * @g2 <requires-id/>
 *
 * @package GalleryCore
 * @subpackage Classes
 */
class GalleryDerivativeImage_core extends GalleryDerivative {

    /*
     * ****************************************
     *                 Members
     * ****************************************
     */

    /**
     * The width of the image.
     *
     * @g2 <member>
     * @g2   <member-name>width</member-name>
     * @g2   <member-type>INTEGER</member-type>
     * @g2 </member>
     *
     * @var int $_width
     * @access private
     */
    var $_width;

    /**
     * The height of the image.
     *
     * @g2 <member>
     * @g2   <member-name>height</member-name>
     * @g2   <member-type>INTEGER</member-type>
     * @g2 </member>
     *
     * @var int $_height
     * @access private
     */
    var $_height;

    /*
     * ****************************************
     *                 Methods
     * ****************************************
     */

    /**
     * @see GalleryDerivative::canBeViewedInline()
     */
    function canBeViewedInline() {
	return true;
    }

    /**
     * Create a new GalleryDerivativeImage
     *
     * @param int the id of the parent GalleryItem
     * @param int the type of derivative image
     * @return object GalleryStatus a status code
     */
    function create($parentId, $derivativeType) {
	global $gallery;

	if ($derivativeType != DERIVATIVE_TYPE_IMAGE_THUMBNAIL &&
		$derivativeType != DERIVATIVE_TYPE_IMAGE_RESIZE &&
		$derivativeType != DERIVATIVE_TYPE_IMAGE_PREFERRED) {
	    return GalleryStatus::error(ERROR_BAD_PARAMETER,
					__FILE__, __LINE__,
					"Unknown derivative type: $derivativeType");
	}

	/* We can't have more than one THUMBNAIL or PREFERRED */
	if ($derivativeType == DERIVATIVE_TYPE_IMAGE_THUMBNAIL ||
	    $derivativeType == DERIVATIVE_TYPE_IMAGE_PREFERRED) {

	    $query = '
	    SELECT
	      COUNT([GalleryChildEntity::id])
	    FROM
	      [GalleryChildEntity], [GalleryDerivative]
	    WHERE
	      ([GalleryChildEntity::parentId] = ?
	       AND [GalleryDerivative::derivativeType] = ?)
	      AND ([GalleryChildEntity::id] = [GalleryDerivative::id])
	    ';

	    list($ret, $searchResults) =
		$gallery->search($query, array($parentId, $derivativeType));
	    if ($ret->isError()) {
		return $ret->wrap(__FILE__, __LINE__);
	    }

	    $result = $searchResults->nextResult();
	    if ($result[0] > 0) {
		return GalleryStatus::error(ERROR_COLLISION, __FILE__, __LINE__,
		    sprintf('Too many thumbnails or preferreds (type: %s, count: %d)',
			    $derivativeType, $result[0]));
	    }
	}

	$ret = parent::create($parentId);
	if ($ret->isError()) {
	    return $ret->wrap(__FILE__, __LINE__);
	}

	/* Save our derivative type */
	$this->setDerivativeType($derivativeType);

	return GalleryStatus::success();
    }

    /**
     * Rebuild the cache.
     *
     * Only applicable if isDerative() returns true.  Break apart the
     * derivative commands and feed them into the appropriate graphics toolkits
     * to perform the transformation necessary to create this derivative from
     * its source.
     *
     * @access public
     * @return object GalleryStatus a status code
     */
    function rebuildCache() {
	global $gallery;

	/* Figure out our target path */
	list($ret, $destPath) = $this->fetchPath();
	if ($ret->isError()) {
	    return $ret->wrap(__FILE__, __LINE__);
	}

	$ret = parent::rebuildCache();
	if ($ret->isError()) {
	    return $ret->wrap(__FILE__, __LINE__);
	}

	/* Update our dimensions */
	$mimeType = $this->getMimeType();
	list ($ret, $toolkit) = GalleryCoreApi::getToolkitByProperty($mimeType, 'dimensions');
	if ($ret->isError()) {
	    return $ret->wrap(__FILE__, __LINE__);
	}

	if (isset($toolkit)) {
	    list ($ret, $dimensions) = $toolkit->getProperty($mimeType, 'dimensions', $destPath);
	    if ($ret->isError()) {
		return $ret->wrap(__FILE__, __LINE__);
	    }

	    $this->setWidth($dimensions[0]);
	    $this->setHeight($dimensions[1]);
	}

	return GalleryStatus::success();
    }

    /**
     * @see GalleryDerivative::render()
     */
    function render($format, $item, $params) {
 	global $gallery;

	switch($format) {
	case 'HTML':
	    $urlGenerator =& $gallery->getUrlGenerator();
	    $src = $urlGenerator->generateUrl(array('view' => 'core.DownloadItem',
						    'itemId' => $this->getId(),
						    'serialNumber' => $this->getSerialNumber()));

	    list ($width, $height) = array($this->getWidth(), $this->getHeight());

	    /* Shrink our dimensions if necessary */
	    if (isset($params['maxSize'])) {
		list ($width, $height) =
		    GalleryUtilities::shrinkDimensionsToFit($width, $height, $params['maxSize']);
		unset($params['maxSize']);
	    }

	    $sizeStr = '';
	    if ($width > 0 && $height > 0) {
		$sizeStr = sprintf(' width="%s" height="%s"', $width, $height);
	    }
	    if (!isset($params['alt'])) {
		$params['alt'] = $item->getTitle() ? $item->getTitle() : $item->getPathComponent();
	    }
	    if (!isset($params['longdesc'])) {
		$params['longdesc'] = preg_replace('/[\r\n]+/', ' ', $item->getDescription());
	    }

	    $html = sprintf('<img src="%s"%s', $src, $sizeStr);
	    unset($params['fallback']);
	    foreach ($params as $attr => $value) {
		if (isset($value)) {
		    $html .= " $attr=\"$value\"";
		}
	    }
	    return $html . '/>';

	default:
	    return null;
	}
    }
}

include(dirname(__FILE__) . '/interfaces/GalleryDerivativeImage.inc');
?>
