<?php 
/**
* @version $Id: notify.php,v 1.4 2005/01/27 19:33:25 soeren_nb Exp $
* @package mambo-phpShop
* @subpackage Payment
* @copyright (C) 2004-2005 Soeren Eberhardt
*
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* mambo-phpShop is Free Software.
* mambo-phpShop comes with absolute no warranty.
*
* www.mambo-phpshop.net
*
* PayPal IPN Handler
*/

if ($_POST) {
    
    define('_VALID_MOS', '1');
    global $mosConfig_absolute_path, $mosConfig_live_site, $mosConfig_lang;
    
    /*** access Mambo's configuration file ***/
        $my_path = dirname($_SERVER['SCRIPT_FILENAME']);
        $mambo_path = str_replace("administrator/components/com_phpshop", "", $my_path);
        
        require_once($mambo_path.'configuration.php');
        require_once($mambo_path.'includes/database.php');
        require_once($mosConfig_absolute_path. '/administrator/components/com_phpshop/mos_4.6_code.php');
        
        global $database;
        $database = new database( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
        
        // load Mambo Language File
        if (file_exists( $mosConfig_absolute_path. '/language/'.$mosConfig_lang.'.php' ))
          require_once( $mosConfig_absolute_path. '/language/'.$mosConfig_lang.'.php' );
        else
          require_once( $mosConfig_absolute_path. '/language/english.php' );
    /*** END of Mambo config ***/
    
    
    /*** mambo-phpShop part ***/
        define('PHPSHOPPATH', $mosConfig_absolute_path.'/administrator/components/com_phpshop/');
        
        require_once(PHPSHOPPATH."phpshop.cfg.php");

        
        require_once( $mosConfig_absolute_path . '/includes/phpmailer/class.phpmailer.php');
        $mail = new mosPHPMailer();
        $mail->PluginDir = $mosConfig_absolute_path . '/includes/phpmailer/';
        $mail->SetLanguage("en", $mosConfig_absolute_path . '/includes/phpmailer/language/');
              
        /* load the mambo-phpShop Language File */
        if (file_exists( ADMINPATH. 'languages/'.$mosConfig_lang.'.php' ))
          require_once( ADMINPATH. 'languages/'.$mosConfig_lang.'.php' );
        else
          require_once( ADMINPATH. 'languages/english.php' );
        
        /* Load the PayPal Configuration File */ 
        require_once( CLASSPATH. 'payment/ps_paypal.cfg.php' );
        
        /* Load the mambo-phpShop database class */
        require_once( CLASSPATH. 'ps_database.php' );
        
    /*** END mambo-phpShop part ***/
    
    /**
    * Read post from PayPal system and create reply
    * starting with: 'cmd=_notify-validate'...
    * then repeating all values sent: that's our VALIDATION.
    **/
    $workstring = 'cmd=_notify-validate'; // Notify validate
    $i = 1;
    foreach ($_POST as $ipnkey => $ipnval) {
        if (get_magic_quotes_gpc())
            // Fix issue with magic quotes
            $ipnval = stripslashes ($ipnval);
            
        if (!eregi("^[_0-9a-z-]{1,30}$",$ipnkey)  || !strcasecmp ($ipnkey, 'cmd'))  { 
            // ^ Antidote to potential variable injection and poisoning
            unset ($ipnkey); 
            unset ($ipnval); 
        } 
        // Eliminate the above
        // Remove empty keys (not values)
        if (@$ipnkey != '') { 
          //unset ($_POST); // Destroy the original ipn post array, sniff...
          $workstring.='&'.@$ipnkey.'='.urlencode(@$ipnval); 
        }
        echo "key ".$i++.": $ipnkey, value: $ipnval<br />";
    } // Notify string
    
    
    $paypal_receiver_email = PAYPAL_EMAIL;
    $item_name = trim(stripslashes($_POST['item_name']));
    $item_number = trim(stripslashes($_POST['item_number']));
    $payment_status = trim(stripslashes($_POST['payment_status']));
    $payment_gross = trim(stripslashes($_POST['payment_gross']));
    $txn_id = trim(stripslashes($_POST['txn_id']));
    $receiver_email = trim(stripslashes($_POST['receiver_email']));
    $payer_email = trim(stripslashes($_POST['payer_email']));
    $payment_date = trim(stripslashes($_POST['payment_date']));
    $invoice =  trim(stripslashes($_POST['invoice']));
    $quantity = trim(stripslashes($_POST['quantity']));
    $pending_reason = trim(stripslashes($_POST['pending_reason']));
    $payment_method = trim(stripslashes($_POST['payment_method']));
    $first_name = trim(stripslashes($_POST['first_name']));
    $last_name = trim(stripslashes($_POST['last_name']));
    $address_street = trim(stripslashes($_POST['address_street']));
    $address_city = trim(stripslashes($_POST['address_city']));
    $address_state = trim(stripslashes($_POST['address_state']));
    $address_zipcode = trim(stripslashes($_POST['address_zip']));
    $address_country = trim(stripslashes($_POST['address_country']));
    $payer_email = trim(stripslashes($_POST['payer_email']));
    $address_status = trim(stripslashes($_POST['address_status']));
    $payer_status = trim(stripslashes($_POST['payer_status']));
    $notify_version = trim(stripslashes($_POST['notify_version'])); 
    $verify_sign = trim(stripslashes($_POST['verify_sign'])); 
    $business = trim(stripslashes($_POST['business'])); 
    $custom = trim(stripslashes($_POST['custom'])); 
    $txn_type = trim(stripslashes($_POST['txn_type'])); 
    
    /*
    if($paypal_receiver_email != "$receiver_email"){
        $error_message .= "Error code 501. Possible fraud. Error with receiver_email. receiver_email = $receiver_email\n";
        $error++;
    }  
    
    if ((!preg_match("/^65.206/", $REMOTE_ADDR)) || (!preg_match("/^64.04/", $REMOTE_ADDR))){
           $error_message .= "Error code 506. Possible fraud. Error with REMOTE IP ADDRESS = $REMOTE_ADDR . The remote address of the script posting to this notify script does not match a valid PayPal ip address\n";
           $error++;
    } 
    */
    //--------------------------------------------
    // Create message to post back to PayPal...
    // Open a socket to the PayPal server...
    //--------------------------------------------
    //$header = "POST /testing/ipntest.php HTTP/1.0\r\n";
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen ($workstring) . "\r\n\r\n";
    //$fp = fsockopen ("www.eliteweaver.co.uk", 80, $errno, $errstr, 30);
    $fp = fsockopen ("www.paypal.com", 80, $errno, $errstr, 30);
    
    //----------------------------------------------------------------------
    // Check HTTP connection made to PayPal OK, If not, print an error msg
    //----------------------------------------------------------------------
    if (!$fp) {
        echo "$errstr ($errno)";
        $res = "FAILED";
    
    }
    
    //--------------------------------------------------------
    // If connected OK, write the posted values back, then...
    //--------------------------------------------------------
    else {
      fputs ($fp, $header . $workstring);
    
      while (!feof($fp)) {
           $res .= fgets ($fp, 1024);
        }
      fclose ($fp);
      
      echo "Response from PayPal: " . $res;
      
      // remove post headers if present.
      $res = preg_replace("'Content-type: text/plain'si","",$res);
      
      //-------------------------------------------
      // ...read the results of the verification...
      // If VERIFIED = continue to process the TX...
      //-------------------------------------------
        if (eregi ( "VERIFIED", $res)) {
            //----------------------------------------------------------------------
            // If the payment_status is Completed... Get the password for the product
            // from the DB and email it to the customer.
            //----------------------------------------------------------------------
            if (eregi ("Completed", $payment_status)) {
                 
                 $qv = "SELECT order_id, order_number FROM #__pshop_orders ";
                 $qv .= "WHERE order_number='".$invoice."'";
                 $dbbt = new ps_DB;
                 $dbbt->query($qv);
                 $dbbt->next_record();
                 $order_id = $dbbt->f("order_id");
                 if (empty($order_id)) {
                    $mail->From = $mosConfig_mailfrom;
                    $mail->FromName = $mosConfig_fromname;
                    $mail->AddAddress($receiver_email);
                    $mail->Subject = "PayPal IPN txn on your site";
                    $mail->Body = "The right order_id wasn't found during a PayPal transaction on your website";
                    $mail->Send();
                 }
    
                // UPDATE THE ORDER STATUS to 'VALID'
                $d['order_id'] = $order_id;
                $d['order_status'] = PAYPAL_VERIFIED_STATUS;
                require_once ( CLASSPATH . 'ps_order.php' );
                $ps_order= new ps_order;
                $ps_order->order_status_update($d);
                $mail->From = $mosConfig_mailfrom;
                $mail->FromName = $mosConfig_fromname;
                $mail->AddAddress($receiver_email);
                $mail->Subject = "PayPal IPN txn on your site";
                $mail->Body = "A PayPal transaction for you has been made on your website!";
                $mail->Send();
                echo "Complete PayPal TX";
            }
            else { 
                //----------------------------------------------------------------------
                // If the payment_status is not Completed... do nothing but mail
                //----------------------------------------------------------------------
                // UPDATE THE ORDER STATUS to 'INVALID'
                $d['order_id'] = $order_id;
                $d['order_status'] = PAYPAL_INVALID_STATUS;
                require_once ( CLASSPATH . 'ps_order.php' );
                $ps_order= new ps_order;
                $ps_order->order_status_update($d);
                $mail->From = $mosConfig_mailfrom;
                $mail->FromName = $mosConfig_fromname;
                $mail->AddAddress($receiver_email);
                $mail->Subject = "PayPal IPN txn on your site";
                $mail->Body = "Incomplete PayPal TX... An incomplete transaction requires your attention.";
                $mail->Send();
                
            }
        }
        //----------------------------------------------------------------
        // ..If UNVerified - It's 'Suspicious' and needs investigating!
        // Send an email to yourself so you investigate it.
        //----------------------------------------------------------------
        elseif (eregi ("INVALID", $res)) {
                $mail->From = $mosConfig_mailfrom;
                $mail->FromName = $mosConfig_fromname;
                $mail->AddAddress($receiver_email);
                $mail->Subject = "PayPal IPN txn on your site";
                $mail->Body = "Invalid PayPal TX... An invalid transaction requires your attention.";
                $mail->Send();
                echo "Invalid PayPal TX... An invalid transaction requires your attention.";
        }
        else {
                $mail->From = $mosConfig_mailfrom;
                $mail->FromName = $mosConfig_fromname;
                $mail->AddAddress($receiver_email);
                $mail->Subject = "PayPal IPN txn on your site";
                $mail->Body = "An error occured while processing a paypal transaction. $res";
                $mail->Send();
        }
    }
}
?>
