<?php
/*
 * $RCSfile: IPN.inc,v $
 *
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2004 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/**
 * 
 * @package CheckoutPaypal
 * @subpackage UserInterface
 * @author Matthew Turnbull <matthew.turnbull@messagescan.net>
 */


/**
 * This controller will handle the postback for PayPal IPN
 *
 * @package Checkout
 * @subpackage UserInterface
 *
 */
class IPNController extends GalleryController {

    /**
     * @see GalleryController::handleRequest()
     */
  function handleRequest($form) {
		global $gallery;
		GalleryCoreApi::requireOnce('classes/GalleryCheckoutPaypalIPNHelper.class');

		$IPNpost = GalleryUtilities::getRequestVariablesNoPrefix('invoice',
									 'txn_id',
									 'payment_status',
									 'payment_date',
									 'verify_sign',
									 'first_name',
									 'last_name',
									 'payer_email',
									 'mc_gross',
									 'address_name',
									 'address_street',
									 'address_city',
									 'address_state',
									 'address_zip',
									 'address_country',
									 'memo' );

		/* Retrieve the CheckoutTransaction for this IPN */
		list ($ret, $transaction) = GalleryCoreApi::loadEntitiesById($IPNpost[0]);
		if ($ret) {
		    return array($ret->wrap(__FILE__, __LINE__), null);
		}

		if (!isset($transaction)) {
		    return array(GalleryCoreApi::error(ERROR_MISSING_OBJECT, __FILE__, __LINE__),
				 null);
		}

		/* Count the existing Paypal child transactions */
		list ($ret, $ppTransactions) =
		    GalleryCheckoutPaypalIPNHelper::fetchPpTxnCounts($transaction->getId());
		if ($ret) {
		    return array($ret->wrap(__FILE__, __LINE__), null);
		}

		/* Has this transaction already been posted back by PayPal? If not, create a record*/
		if ( !isset($ppTransactions[$transaction->getId()]) ) {
		    /* Get a write lock for the transaction and refresh from database */
		    list ($ret, $lockId) = GalleryCoreApi::acquireWriteLock(array($transaction->getId()));
		    if ($ret) {
			return array($ret->wrap(__FILE__, __LINE__), null);
		    }
		    list ($ret, $transaction) = $transaction->refresh();
		    if ($ret) {
			return array($ret->wrap(__FILE__, __LINE__), null);
		    }
		    
		    /* Set the IPN information into the original transaction */
		    $transaction->setFirstName($IPNpost[5]);
		    $transaction->setLastName($IPNpost[6]);
		    $transaction->setEmail($IPNpost[7]);
		    $transaction->setRecipientName($IPNpost[9]);
		    $transaction->setAddress1($IPNpost[10]);
		    $transaction->setAddress2($IPNpost[11]);
		    $transaction->setAddress3($IPNpost[12]);
		    $transaction->setAddressZip($IPNpost[13]);
		    $transaction->setAddressCountry($IPNpost[14]);
		    $transaction->setcustNotes('PayPal notes: ' . $IPNpost[15]);
            $transaction->setPaymentPlugin('checkoutpaypal');
            $transaction->setFlagPaid(TRUE);

		    /* Save the modified transaction */
		    $ret = $transaction->save();
		    if ($ret) {
			return array($ret->wrap(__FILE__, __LINE__), null);
		    }

		    /* Release our lock */
		    $ret = GalleryCoreApi::releaseLocks($lockId);
		    if ($ret) {
			return array($ret->wrap(__FILE__, __LINE__), null);
		    }
		}

		/* Add a new Paypal transaction for this IPN */
		list ($ret, $ppTransaction) =
		    GalleryCoreApi::newFactoryInstance('GalleryEntity', 'GalleryCheckoutPaypalIPN');
		if ($ret) {
		    return array($ret->wrap(__FILE__, __LINE__), null);
		}
		if (!isset($ppTransaction)) {
		    return array(GalleryCoreApi::error(ERROR_MISSING_OBJECT, __FILE__, __LINE__), null);
		}
		$ret = $ppTransaction->create($transaction->getId());
		if ($ret) {
		    return array($ret->wrap(__FILE__, __LINE__), null);
		}

		$ppTransaction->setppId($IPNpost[1]);
		$ppTransaction->setppStatus($IPNpost[2]);
		$ppTransaction->setppDate($IPNpost[3]);
		$ppTransaction->setppSign($IPNpost[4]);
		$notes = time() . ' PayPal IPN postback received';
		if ( ((float) $transaction->getamount()) != ((float) $IPNpost[8]) ) {
		    $notes .= '<br>' . time() . ' WARNING: PayPal amount (' . $IPNpost[8] . ') does not match our records (' . $transaction->getamount() . ')';
		} else {
		    $notes .= '<br>' . time() . ' PayPal amount matches our records';
            /* Fire an event to say we've got cleared payment */
            $event = GalleryCoreApi::newEvent('GalleryCheckout::setflagCleared');
            list ($ret) = GalleryCoreApi::postEvent($event);
            if ($ret) {
                return $ret->wrap(__FILE__, __LINE__);
            }
		}
		$notes .= '<br>PayPal notes: ' . $IPNpost[15];		
		$ppTransaction->setnotes($notes);
		
		$ppTransaction ->save();
		if ($ret) {
	            return array($ret->wrap(__FILE__, __LINE__), null);
		}

		$results['redirect']['view'] = '';			
		$results['status'] = array();
		$results['error'] = array();
		$results['isError'] = false;
		
		return array(null, $results);
	 
	}
}
?>