<?php
class paypal_class extends \stdClass {
	var $last_error;         // holds the last error encountered
	var $ipn_log;            // bool: log IPN results to text file?
	var $ipn_log_file;       // filename of the IPN log
	var $ipn_response;       // holds the IPN response from paypal
	var $ipn_data = array(); // array contains the POST values for IPN
	var $fields   = array();   // array holds the fields to submit to paypal
	var $sandbox;

	function __construct() {
		$this->sandbox    = wpj_get_option( 'wpjobster_paypal_enable_sandbox' );
		$this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
		if ( $this->sandbox == 'yes' ) $this->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';

		$this->last_error   = '';
		$this->ipn_log_file = get_theme_root() . '/wpjobster/lib/plugins/wpjobster-paypal/ipn_results.log';
		$this->ipn_log      = false;
		$this->ipn_response = '';

		$this->add_field( 'rm', '2' );
		$this->add_field( 'cmd', '_xclick' );
	}

	function paypal_class() { self::__construct(); }

	function add_field( $field, $value ) { $this->fields["$field"] = $value; }

	function submit_paypal_post() {
		if ( wpj_get_option( 'wpjobster_paypal_enable_secure' ) == 'yes' )
			$this->fields = array( 'cmd' => '_s-xclick', 'encrypted' => $this->paypal_encrypt( $this->fields ) );

		wpj_display_gateway_form( $this->fields, $this->paypal_url );
	}

	function validate_ipn() {
		$req = 'cmd=_notify-validate';

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

		$ch = curl_init( $this->paypal_url );

		curl_setopt( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
		curl_setopt( $ch, CURLOPT_POST, 1 );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER,1 );
		curl_setopt( $ch, CURLOPT_POSTFIELDS, $req );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 1 );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
		curl_setopt( $ch, CURLOPT_FORBID_REUSE, 1 );
		curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Connection: Close' ) );

		$res = curl_exec( $ch );

		curl_close( $ch );

		if ( ! empty( $res ) && strcmp( $res, "VERIFIED" ) == 0 ) { // valid IPN transaction
			$this->log_ipn_results( true );
			return true;

		} else { // invalid IPN transaction
			$this->last_error = 'IPN Validation Failed.';
			$this->log_ipn_results( false );
			return false;

		}
	}

	function log_ipn_results( $success ) {
		if ( ! $this->ipn_log ) return false;

		// Timestamp
		$text = '['.date('m/d/Y g:i A').'] - ';

		// Success or failure being logged?
		if ( $success ) $text .= "SUCCESS!\n";
		else $text .= 'FAIL: ' . $this->last_error . "\n";

		// Log the POST variables
		$text .= "IPN POST Vars from Paypal:\n";
		foreach ( $this->ipn_data as $key => $value ) {
			$text .= "$key=$value, ";
		}

		// Log the response from the paypal server
		$text .= "\nIPN Response from Paypal Server:\n " . $this->ipn_response;

		// Write to log
		$fp = fopen( $this->ipn_log_file, 'a' );
		fwrite( $fp, $text . "\n\n" );

		fclose( $fp );
	}

	function paypal_encrypt( $hash ) {
		$user_info = posix_getpwuid( posix_getuid() );

		// private key file to use
		$MY_KEY_FILE = $user_info['dir'] . "/paypal/wpjobster_prvkey.pem";

		// public certificate file to use
		$MY_CERT_FILE = $user_info['dir'] . "/paypal/wpjobster_pubcert.pem";

		// paypal's public certificate
		$PAYPAL_CERT_FILE = $user_info['dir'] . "/paypal/paypal_cert.pem";

		// path to the openssl binary
		$OPENSSL = "/usr/bin/openssl";


		if ( ! file_exists( $MY_KEY_FILE ) ) echo "ERROR: MY_KEY_FILE $MY_KEY_FILE not found\n";

		if ( ! file_exists( $MY_CERT_FILE ) ) echo "ERROR: MY_CERT_FILE $MY_CERT_FILE not found\n";

		if ( ! file_exists( $PAYPAL_CERT_FILE ) ) echo "ERROR: PAYPAL_CERT_FILE $PAYPAL_CERT_FILE not found\n";


		// assign build notation for PayPal support
		$hash['bn']= 'StellarWebSolutions.PHP_EWP2';

		$data = "";
		foreach ( $hash as $key => $value ) {
			if ( $value != "" ) $data .= "$key=$value\n";
		}

		$openssl_cmd = "($OPENSSL smime -sign -signer $MY_CERT_FILE -inkey $MY_KEY_FILE " .
					 "-outform der -nodetach -binary <<_EOF_\n$data\n_EOF_\n) | " .
					 "$OPENSSL smime -encrypt -des3 -binary -outform pem $PAYPAL_CERT_FILE";

		exec( $openssl_cmd, $output, $error );

		if ( ! $error ) return implode( "\n", $output );
		else return "ERROR: encryption failed";
	}
}
