<?php
/*
 * $RCSfile: PhotoAccessHelper.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.
 */

/**
 * @package PhotoAccess
 * @version $Revision: 1.19 $ $Date: 2005/08/23 03:49:49 $
 * @author Bharat Mediratta <bharat@menalto.com>
 */

/**
 * This is a helper class for interacting with PhotoAccess.com
 *
 * @package PhotoAccess
 * @subpackage Classes
 *
 */
class PhotoAccessHelper {

    /**
     * Print the items on photoaccess.com and provide them with the given return url
     *
     * @return array object GalleryStatus a status code
     *               string the url to the photoaccess.com cart
     * @static
     */
    function printPhotos($cartItemIds, $returnUrl) {
	global $gallery;
	$itemIds = array_keys($cartItemIds);

	/* Load the necessary item data */
	list ($ret, $items) = GalleryCoreApi::loadEntitiesById($itemIds);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	list ($ret, $thumbnails) = GalleryCoreApi::fetchThumbnailsByItemIds($itemIds);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	list ($ret, $resizes) = GalleryCoreApi::fetchResizesByItemIds($itemIds);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	list ($ret, $preferreds) = GalleryCoreApi::fetchPreferredsByItemIds($itemIds);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	$ret = GalleryCoreApi::studyPermissions($itemIds);
	if ($ret->isError()) {
	    return array($ret->wrap(__FILE__, __LINE__), null);
	}

	$session =& $gallery->getSession();
	$cartUrlFragment = $session->get('photoaccess.cartUrlFragment');

	/* If we don't have a cart url, that means we don't have a session so start with a new url */
	$photoAccessServer = 'www.photoaccess.com';
	if (empty($cartUrlFragment)) {
	    $cartUrlFragment = '/buy/anonCartXML.jsp';
	}

	$urlGenerator =& $gallery->getUrlGenerator();

	/* Assemble all our data */
	$entries = array();
	foreach ($items as $item) {
	    $itemId = $item->getId();
	    $entry = array();

	    list ($ret, $permissions) = GalleryCoreApi::getPermissions($itemId);
	    if ($ret->isError()) {
		return array($ret->wrap(__FILE__, __LINE__), null);
	    }

	    if (isset($permissions['core.viewSource'])) {
		$source = isset($preferreds[$itemId]) ? $preferreds[$itemId] : $item;
	    } else if (isset($permissions['core.viewResizes']) && !empty($resizes[$itemId])) {
		$maxSize = null;
		foreach ($resizes[$itemId] as $resize) {
		    $size = $resize->getDerivativeSize();
		    if (!isset($maxSize) || $size > $maxSize) {
			$source = $resize;
			$maxSize = $size;
		    }
		}
	    } else if (isset($thumbnails[$itemId])) {
		$source = $thumbnails[$itemId];
	    } else {
		continue;
	    }

	    $entry['id'] = $source->getId();
	    $entry['imageUrl'] = $urlGenerator->generateUrl(
		array('view' => 'core.DownloadItem', 'itemId' => $source->getId()),
		true);

	    if (isset($thumbnails[$itemId])) {
		$entry['thumbUrl'] = $urlGenerator->generateUrl(
		    array('view' => 'core.DownloadItem',
			  'itemId' => $thumbnails[$itemId]->getId()),
		    true);
	    } else {
		$entry['thumbUrl'] = '';
	    }
	    $entry['imageWidth'] = $source->getWidth();
	    $entry['imageHeight'] = $source->getHeight();

	    $entries[] = $entry;
	    /* We should scan the results for a "200 OK" result */
	}

	/* Turn our data into an XML request like this:
	 *
	 * <add-cart-request cobrand="CB_GP"
	 *                   pricelist="1"
	 *                   entry-page="/buy/anonCart.jsp"
	 *                   return-url="http://localhost/anon/test.html">
	 *     <image id="1" url="http://localhost/anon/John.jpg"
	 *                   thumb-url="http://localhost/anon/John_BigThumb.jpg"
	 *                   height="1200"
	 *                   width="1600"/>
	 *     <image id="2" url="http://localhost/anon/Jig.jpg"
	 *                   thumb-url="http://localhost/anon/Jig_BigThumb.jpg"
	 *                   height="1200"
	 *                   width="1600"/>
	 * </add-cart-request>
	 */
	$lines = array();
	$lines[] = sprintf('<add-cart-request cobrand="CB_GP" pricelist="1" ' .
			   'entry-page="/buy/anonCart.jsp" return-url="%s">', $returnUrl);
	for ($i = 0; $i < sizeof($entries); $i++) {
	    $lines[] = sprintf('<image id="%d" url="%s" thumb-url="%s" height="%d" width="%d"/>',
                $entries[$i]['id'], $entries[$i]['imageUrl'], $entries[$i]['thumbUrl'],
                $entries[$i]['imageWidth'], $entries[$i]['imageHeight']);
	}
	$lines[] = '</add-cart-request>';

	$postData = array();
	$postData['cb'] = 'CB_GP';
	$postData['xml_request'] = join('', $lines);

	$gallery->guaranteeTimeLimit(30);
	$cartUrl = 'http://' . $photoAccessServer . $cartUrlFragment;
	if ($gallery->getDebug()) {
	    $gallery->debug('Post data:');
	    $gallery->debug_r($postData, true);
	}
	list ($body, $response, $headers) = GalleryCoreApi::postToWebPage(
            $cartUrl, $postData,
            array('User-Agent' => GalleryUtilities::getServerVar('HTTP_USER_AGENT')));

	/* Expect a response of the form:
	 *
	 * <add-cart-response request-err="Error: unable to parse request"/>
	 *
	 * or:
	 *
	 * <add-cart-response
	 *   request-url="/buy/anonCartXML.jsp;jsessionid=XXXXXXXX?cb=CB_GP&#38;svr=clay"
	 *   redirect-url="/buy/anonCart.jsp;jsessionid=XXXXXXXX?cb=CB_GP&#38;svr=clay"/>
	 */
	if ($gallery->getDebug()) {
	    $gallery->debug('Response Data');
	    $gallery->debug_r($body, true);
	}
	if (preg_match('{<add-cart-response\s*request-url="(\S+)"\s*redirect-url="(\S+)"/>}',
		       $body, $matches)) {
	    $cartUrlFragment = str_replace('&#38;', '&', $matches[1]);
	    $session->put('photoaccess.cartUrlFragment', $cartUrlFragment);
	    $redirectUrl = 'http://' . $photoAccessServer . str_replace('&#38;', '&', $matches[2]);
	} else {
	    $redirectUrl =
		$urlGenerator->generateUrl(array('view' => 'photoaccess.FulfillmentError'));
	}

	return array(GalleryStatus::success(), $redirectUrl);
    }
}
?>
