<?php
  /**
   * AlertPay IPN
   *
   * @package Digital Downloads Pro
   * @author wojoscripts.com
   * @copyright 2010
   * @version $Id: ipn.php,<?php echo  2010-08-10 21:12:05 gewa Exp $
   */
  define("_VALID_PHP", true);
  
  
  if (isset($_POST['payment_status'])) {
      require_once("../../init.php");
	  
      /* only for debuggin purpose. Create logfile.txt and chmot to 0777
       ob_start();
       echo '<pre>';
       print_r($_POST);
       echo '</pre>';
       $logInfo = ob_get_contents();
       ob_end_clean();
       
       $file = fopen('logfile.txt', 'a');
       fwrite($file, $logInfo);
       fclose($file);
    */ 

      $req = 'cmd=_notify-validate';
      
      foreach ($_POST as $key => $value) {
          $value = urlencode(stripslashes($value));
          $req .= '&' . $key . '=' . $value;
      }
      $demo = getValue("demo", "gateways", "name = 'paypal'");
	  
	  $url = ($demo == '0') ? 'www.sandbox.paypal.com' : 'www.paypal.com';
      
      $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($url, 80, $errno, $errstr, 30);
      
      $payment_status = $_POST['payment_status'];
      $receiver_email = $_POST['business'];
	  $payer_email = $_POST['payer_email'];
	  $payer_status = $_POST['payer_status'];
	  $mc_currency = $_POST['mc_currency'];
	  $mc_fee = $_POST['mc_fee'];
	  
	  list($user_id, $sesid) = explode('_',$_POST['custom']);
      $mc_gross = $_POST['mc_gross'];
      $txn_id = $_POST['txn_id'];
      
      $getxn_id = $core->verifyTxnId($txn_id);
	  
	  $cartrow = $content->getCartContent($sesid);
	  $totalrow = $content->getCartTotal($sesid);
	  $gross = $totalrow['total'] - $totalrow['coupon'];
	  
      $pp_email = getValue("extra", "gateways", "name = 'paypal'");
      
      if (!$fp) {
          echo $errstr . ' (' . $errno . ')';
      } else {
          fputs($fp, $header . $req);
          
          while (!feof($fp)) {
              $res = fgets($fp, 1024);
              if (strcmp($res, "VERIFIED") == 0) {
                  if (preg_match('/Completed/', $payment_status)) {
                      if ($receiver_email == $pp_email && $mc_gross == $gross && $getxn_id == true) {
							if($cartrow) {
								foreach ($cartrow as $crow) {
									$data = array(
											'txn_id' => sanitize($txn_id),
											'pid' => $crow['pid'],
											'uid' => intval($user_id),
											'downloads' => 0,
											'file_date' => time(),
											'ip' => sanitize($_SERVER['REMOTE_ADDR']),
											'created' => "NOW()",
											'payer_email' => sanitize($payer_email),
											'payer_status' => sanitize($payer_status),
											'item_qty' => $crow['total'],
											'price' => $crow['total'] * $crow['price'],
											'mc_fee' => floatval($mc_fee),
											'currency' => sanitize($mc_currency),
											'pp' => "PayPal",
											'status' => 1,
											'active' => 1
									);
									$db->insert("transactions", $data);
								}
								
								unset($crow);
							}

                            /* == Notify Administrator == */
                          require_once(BASEPATH . "lib/class_mailer.php");
                          $row2 = $core->getRowById("email_templates", 5);
						  $user = $core->getRowById("users", $user_id);
                          
                          $body = str_replace(array('[USERNAME]', '[STATUS]', '[TOTAL]', '[PP]', '[IP]'), 
						  array($user['username'], "Completed", $core->formatMoney($gross), "PayPal", $_SERVER['REMOTE_ADDR']), $row2['body']);
                          
                          $newbody = cleanOut($body);
                          
                          $mailer = $mail->sendMail();
                          $message = Swift_Message::newInstance()
								  ->setSubject($row2['subject'])
								  ->setTo(array($core->site_email => $core->site_name))
								  ->setFrom(array($core->site_email => $core->site_name))
								  ->setBody($newbody, 'text/html');
                          
                          $mailer->send($message);

                          /* == Notify User == */
                          $row3 = $core->getRowById("email_templates", 8);
						  $val = '
						  <table border="0" cellpadding="4" cellspacing="2">';
							$val .= '
							<thead>
							  <tr>
								<td width="20"><strong>#</strong></td>
								<td><strong>Product Name</strong></td>
								<td><strong>Product Price</strong></td>
								<td><strong>Quantity</strong></td>
								<td><strong>Total Price</strong></td>
							  </tr>
							</thead>
							<tbody>';
							$i = 0;
							foreach ($cartrow as $ccrow) {
								$i++;
								$val .= '
								<tr>
								  <td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $i . '.</td>
								  <td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . sanitize($ccrow['title'],30,false) . '</td>
								  <td style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $core->formatMoney($ccrow['price']) . '</td>
								  <td align="center" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $ccrow['total'] . '</td>
								  <td align="right" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed">' . $core->formatMoney($ccrow['total'] * $ccrow['price']) . '</td>
								</tr>';
							}
							unset($ccrow);
							$val .= '
							<tr>
							  <td colspan="4" align="right" valign="top" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed"><strong>';
								if ($totalrow['coupon'] != 0) {
								  $val .= 'Discount:<br />';
								}
								$val .= 'Sub Total:<br />
								</strong></td>
							  <td align="right" valign="top" style="border-bottom-width:1px; border-bottom-color:#bbb; border-bottom-style:dashed"><strong>';
								if ($totalrow['coupon'] != 0) {
								  $val .= '- ' . $core->formatMoney($totalrow['coupon']) . '<br />';
								}
								$val .= $core->formatMoney($gross) . '<br />
								</strong>';
								$val .= ' </td>
							</tr>
							<tr>
							  <td colspan="4" align="right" valign="top"><strong style="color:#F00">Grand Total:</strong></td>
							  <td align="right" valign="top"><strong style="color:#F00">' . $core->formatMoney($gross) . '</strong></td>
							</tr>
							  </tbody>
						  </table>';
						  
                          $body3 = str_replace(array('[USERNAME]', '[ITEMS]', '[SITENAME]', '[URL]'), 
						  array($user['username'], $val, $core->site_url, $core->site_name), $row3['body']);
                          
                          $newbody2 = cleanOut($body3);
                          
                          $mailer2 = $mail->sendMail();
                          $message2 = Swift_Message::newInstance()
								  ->setSubject($row3['subject'])
								  ->setTo(array($user['email'] => $user['username']))
								  ->setFrom(array($core->site_email => $core->site_name))
								  ->setBody($newbody2, 'text/html');
                          
                          $mailer2->send($message2);
						  
						  $db->delete("cart", "user_id='" . $sesid . "'");
						  $db->delete("extras", "user_id='" . $sesid . "'");
						  $db->delete("recent", "user_id='" . $sesid . "'");
                      }
					 
                  } else {
                      /* == Failed Transaction= = */
                      require_once(BASEPATH . "lib/class_mailer.php");
                      $row = $core->getRowById("email_templates", 6);
                      $user = getRowById("users", $user_id);


					  $body = str_replace(array('[USERNAME]', '[STATUS]', '[TOTAL]', '[PP]', '[IP]'), 
					  array($user['username'], "Failed", $core->formatMoney($gross), "PayPal", $_SERVER['REMOTE_ADDR']), $row['body']);
                      
                      $newbody = cleanOut($body);
                      
                      $mailer = $mail->sendMail();
                      $message = Swift_Message::newInstance()
							  ->setSubject($row4['subject'])
							  ->setTo(array($core->site_email => $core->site_name))
							  ->setFrom(array($core->site_email => $core->site_name))
							  ->setBody($newbody, 'text/html');
                      
                      $mailer->send($message);

                  }
				  
              }
          }
          fclose($fp);
      }
  }
?>