<?php
$path = "../libraries/";
require_once $path."configuration.php";


if (empty($_POST) || !empty($_GET)) {
	eF_printMessage('Sorry, you can not use this page.');
	exit;
}

try {
    $admin     = getAdministrator();
    $logFolder = $admin -> user['directory'].'/';
    if (!is_dir($logFolder)) {
        $logFolder = '';
    }
} catch (Exception $e) {
    $logFolder = '';
}


$log = fopen($logFolder."ipn.log", "a");
fwrite($log, "ipn - " . gmstrftime ("%b %d %Y %H:%M:%S", time()) . "\n");
$req = 'cmd=_notify-validate';

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

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Host: www.sandbox.paypal.com:80\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);

// assign posted variables to local variables
$fields		= array('settle_amount'        => $_POST['settle_amount'],
					'address_status'       => $_POST['address_status'],
					'payer_id'             => $_POST['payer_id'],
					'tax'                  => $_POST['tax'],
					'address_street'       => $_POST['address_street'],
					'payment_date'         => $_POST['payment_date'],
					'payment_status'       => $_POST['payment_status'],
					'charset'              => $_POST['charset'],
					'address_zip'          => $_POST['address_zip'],
					'first_name'           => $_POST['first_name'],
					'mc_fee'               => $_POST['mc_fee'],
					'address_country_code' => $_POST['address_country_code'],
					'exchange_rate'        => $_POST['exchange_rate'],
					'address_name'         => $_POST['address_name'],
					'notify_version'       => $_POST['notify_version'],
					'settle_currency'      => $_POST['settle_currency'],
					'custom'               => $_POST['custom'],
					'payer_status'         => $_POST['payer_status'],
					'address_country'      => $_POST['address_country'],
					'address_city'         => $_POST['address_city'],
					'quantity'             => $_POST['quantity'],
					'verify_sign'          => $_POST['verify_sign'],
					'payer_email'          => $_POST['payer_email'],
					'txn_id'               => $_POST['txn_id'],
					'payment_type'         => $_POST['payment_type'],
					'last_name'            => $_POST['last_name'],
					'address_state'        => $_POST['address_state'],
					'receiver_email'       => $_POST['receiver_email'],
					'payment_fee'          => $_POST['payment_fee'],
					'receiver_id'          => $_POST['receiver_id'],
					'txn_type'             => $_POST['txn_type'],
					'mc_currency'          => $_POST['mc_currency'],
					'residence_country'    => $_POST['residence_country'],
					'test_ipn'             => $_POST['test_ipn'],
					'payment_gross'        => $_POST['payment_gross'],
					'shipping'             => $_POST['shipping'],
					'status'               => 'completed',
					'timestamp_finish'     => time());

if (!$fp) {
	fwrite($log, "Failed to open HTTP connection!");
} else {
	fputs ($fp, $header . $req);
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);
		if (strcmp ($res, "VERIFIED") == 0) {
			$query = eF_getTableData("paypal_data", "*", "transactionID='".$_POST['custom']."'");
			if (sizeof($query) == 1) {
				if ($query['0']['business'] == $_POST['business'] && (float)$query['0']['mc_gross'] == (float)$_POST['mc_gross'] && $query['0']['item_number'] == $_POST['item_number'] && $query['0']['mc_currency'] == $_POST['mc_currency']){
				    $update = eF_updateTableData("paypal_data", $fields, "transactionID='".$_POST['custom']."'");
				    if ($update && $_POST['payment_status'] == 'Completed') {
				        $lessons_id = explode(", ", $_POST['item_number']);
				        foreach($lessons_id AS $id){
				            if ($id < 100000) {
				                $lesson = new EfrontLesson($id);
				                $lesson -> addUsers($query['0']['user'], 'student');
				            } else {
				                $courseId       = $id - 100000;
				                $editCourse     = new EfrontCourse($courseId);
				                $userType       = 'student';
				                $courseUsers    = $editCourse-> getUsers();                         //Get all users that have this course
				                $nonCourseUsers = $editCourse -> getNonUsers();                     //Get all the users that can, but don't, have this course
				                $users          = array_merge($courseUsers, $nonCourseUsers);       //Merge users to a single array, which will be useful for displaying them
				                if (in_array($query['0']['user'], array_keys($nonCourseUsers))) {
				                    $editCourse -> addUsers($query['0']['user'], $userType);
				                }
				                if (in_array($query['0']['user'], array_keys($courseUsers))) {
				                    $userType != $courseUsers[$query['0']['user']]['user_type'] ? $editCourse -> setRoles($query['0']['user'], $userType) : $editCourse -> removeUsers($query['0']['user']);
				                }
				            }
				        }
				    } elseif ($update && $_POST['txn_type'] == 'subscr_cancel') {
				        $lessons_id = explode(", ", $_POST['item_number']);
				        foreach($lessons_id AS $id){
				            if ($id < 100000) {
				                $lesson = new EfrontLesson($id);
				                $lesson -> removeUsers($query['0']['user']);
				            } else {
				                $courseId   = $id - 100000;
				                $editCourse = new EfrontCourse($courseId);
				                $editCourse -> removeUsers($query['0']['user']);
				            }
				        }
				    } else {
    					$update = eF_updateTableData("paypal_data", array('status' => $_POST['payment_status']), "transactionID='".$_POST['custom']."'");
    				}
				} else {
				    $update = eF_updateTableData("paypal_data", array('status' => 'invalid-data'), "transactionID='".$_POST['custom']."'");
				}
			} else {
			    $update = eF_updateTableData("paypal_data", array('status' => 'wrong-transaction-id'), "transactionID='".$_POST['custom']."'");
			}
			foreach ($_POST as $key => $value){
				$emailtext .= $key . " = " .$value ."\n";
			}
			fwrite($log, "IPN: VERIFIED \n");
			fwrite($log, $emailtext."\n");
			//fwrite($log, $update."\n");
		} elseif (strcmp ($res, "INVALID") == 0) {
			$update = eF_updateTableData("paypal_data", array('status' => 'invalid-ipn'), "transactionID='".$_POST['custom']."'");
			foreach ($_POST as $key => $value){
				$emailtext .= $key . " = " .$value ."\n";
			}
			fwrite($log, "IPN: INVALID \n");
			fwrite($log, $emailtext."\n");
		}
	}
	fclose ($fp);
}
?>