<?php
/*
  $Id: paypal_notify.php,v 1.1 2002/12/01 18:04:24 wilt Exp $
  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Paypal IPN v0.96
  Copyright (c) 2002 Pablo Pasqualino
  http://www.osmosisdc.com

  Released under the GNU General Public License
*/

  include('includes/application_top.php');

  require(DIR_WS_CLASSES . 'order.php');

  $order = new order($HTTP_POST_VARS['item_number']);

  $req = 'cmd=_notify-validate';

  foreach ($HTTP_POST_VARS as $key => $value) {
    $req .= '&' . $key . '=' . urlencode($value);
		$$key = $value;
  }

  $response_verified = '';

  if (MODULE_PAYMENT_PAYPALIPN_CURL=='True') { // IF CURL IS ON, SEND DATA USING CURL (SECURE MODE, TO https://)

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,"https://www.paypal.com/cgi-bin/webscr"); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    $paypal_response = curl_exec($ch);
    curl_close ($ch);

  } else { // ELSE, SEND IT WITH HEADERS (UNSECURE MODE, TO http://)

    $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen ($req) . "\r\n\r\n";
    $fp = fsockopen ("www.paypal.com", 80, $errno, $errstr, 30);

    fputs ($fp, $header . $req);
    while (!feof($fp)) {
      $paypal_response .= fgets($fp, 1024);
    };

    fclose ($fp);

  };

  if (ereg('VERIFIED',$paypal_response)) {
    $response_verified = 1;
    $ipn_result = 'VERIFIED';
  } else if (ereg('INVALID',$paypal_response)) {
    $response_invalid = 1;
    $ipn_result = 'INVALID';
  };

  if ($txn_id && ($response_verified==1 || $response_invalid==1)) {

    $txn_check = tep_db_query("select txn_id from paypalipn_txn where txn_id='$txn_id'");
    if (tep_db_num_rows($txn_check)==0) { // If txn no previously registered, we should register it

      $sql_data_array = array('txn_id' => $txn_id,
                              'ipn_result' => $ipn_result, 
                              'receiver_email' => $receiver_email, 
                              'item_name' => $item_name, 
                              'item_number' => $item_number, 
                              'quantity' => $quantity, 
                              'invoice' => $invoice, 
                              'custom' => $custom, 
                              'option_name1' => $option_name1, 
                              'option_selection1' => $option_selection1, 
                              'option_name2' => $option_name2, 
                              'option_selection2' => $option_selection2, 
                              'num_cart_items' => $num_cart_items, 
                              'payment_status' => $payment_status, 
                              'pending_reason' => $pending_reason,
                              'payment_date' => $payment_date, 
                              'payment_gross' => $payment_gross, 
                              'payment_fee' => $payment_fee, 
                              'mc_gross' => $mc_gross, 
                              'mc_fee' => $mc_fee, 
                              'mc_currency' => $mc_currency, 
                              'txn_type' => $txn_type, 
                              'first_name' => $first_name, 
                              'last_name' => $last_name, 
                              'address_street' => $address_street, 
                              'address_city' => $address_city, 
                              'address_state' => $address_state, 
                              'address_zip' => $address_zip, 
                              'address_country' => $address_country, 
                              'address_status' => $address_status, 
                              'payer_email' => $payer_email, 
                              'payer_id' => $payer_id, 
                              'payer_status' => $payer_status,
                              'payment_type' => $payment_type,
                              'notify_version' => $notify_version,
                              'verify_sign' => $verify_sign);
      tep_db_perform('paypalipn_txn',$sql_data_array);

    } else { // else we update it to the new status

      $sql_data_array = array('payment_status' => $payment_status,
                              'pending_reason' => $pending_reason,
                              'ipn_result' => $ipn_result,
                              'payer_email' => $payer_email, 
                              'payer_id' => $payer_id, 
                              'payer_status' => $payer_status,
                              'payment_type' => $payment_type);

      tep_db_perform('paypalipn_txn',$sql_data_array,'update','txn_id=\''.$txn_id.'\'');

    };

  };

  if ($response_verified==1) {

    if (strtolower($receiver_email)==strtolower(MODULE_PAYMENT_PAYPALIPN_ID)) {

      if ($payment_status=='Completed') {

        if (MODULE_PAYMENT_PAYPALIPN_UPDATE_STOCK_BEFORE_PAYMENT=='False') {

          for ($i=0; $i<sizeof($order->products); $i++) {
            if (STOCK_LIMITED == 'true') {
              if (DOWNLOAD_ENABLED == 'true') {

                $stock_query_raw = "SELECT products_quantity, pad.products_attributes_filename 
                                    FROM " . TABLE_PRODUCTS . " p
                                    LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES . " pa
                                     ON p.products_id=pa.products_id
                                    LEFT JOIN " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad
                                     ON pa.products_attributes_id=pad.products_attributes_id
                                    WHERE p.products_id = '" . tep_get_prid($order->products[$i]['id']) . "'";

                $products_attributes = $order->products[$i]['attributes'];
                $stock_query = tep_db_query($stock_query_raw);
              } else {
                $stock_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
              }
              $stock_values = tep_db_fetch_array($stock_query);

              if ((DOWNLOAD_ENABLED != 'true') || (!$stock_values['products_attributes_filename'])) {
                $stock_left = $stock_values['products_quantity'] - $order->products[$i]['qty'];
              } else {
                $stock_left = $stock_values['products_quantity'];
              }
              tep_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . $stock_left . "' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");

              if ($stock_left < 1) {
                tep_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . tep_get_prid($order->products[$i]['id']) . "'");
              }
            }
          };
        };

        $sql_data_array = array('orders_status' => MODULE_PAYMENT_PAYPALIPN_COMPLETED_TXN_STATUS_ID);

        tep_db_perform(TABLE_ORDERS,$sql_data_array,'update','orders_id='.$item_number);

        $customer_notification = (SEND_EMAILS == 'true') ? '1' : '0';
        $sql_data_array = array('orders_id' => $item_number, 
                                'new_value' => MODULE_PAYMENT_PAYPALIPN_COMPLETED_TXN_STATUS_ID, 
                                'old_value' => 99999, 
                                'date_added' => 'now()', 
                                'customer_notified' => $customer_notification);
        tep_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);



        $email_data = tep_db_query("select * from paypalipn_temp_data where orders_id=".$HTTP_POST_VARS['item_number']);
        $email_data_values = tep_db_fetch_array($email_data);

        tep_mail($email_data_values['email_to'], $email_data_values['email_address'], $email_data_values['email_subject'], $email_data_values['email_text'], STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, '');

				tep_db_query("delete from paypalipn_temp_data where orders_id=".$HTTP_POST_VARS['item_number']);

        $select_customer_id = tep_db_query("select customers_id from orders where orders_id=".$HTTP_POST_VARS['item_number']);
        $customer_id = tep_db_fetch_array($select_customer_id);

				tep_db_query("delete from " .TABLE_CUSTOMERS_BASKET. " where customers_id=".$customer_id['customers_id']);
				tep_db_query("delete from " .TABLE_CUSTOMERS_BASKET_ATTRIBUTES. " where customers_id=".$customer_id['customers_id']);

        if (SEND_EXTRA_ORDER_EMAILS_TO != '') { // send emails to other people
          tep_mail('', SEND_EXTRA_ORDER_EMAILS_TO, $email_data_values['email_subject'], $email_data_values['email_text'], STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, '');
        };

      };

    };

  };
?>