$item_price[1] = $_SESSION["Payment_Amount"];
        $name[1] = $_SESSION["BILLINGDESCRIPTION"];
        $display .= PAYPAL_handlePurchase($items, $quantities, $data, $name, $item_price, 1, 'complete', 0, '', '', $resArray1["PAYMENTINFO_0_TRANSACTIONTYPE"], $resArray1["PAYMENTINFO_0_PAYMENTTYPE"]);
        // Add user to group
        PAYPAL_addToGroup($_SESSION["group_id"], $_USER['uid']);
    }
}
$resArray = CreateRecurringPaymentsProfile();
$ack = strtoupper($resArray["ACK"]);
if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
    //Record profileid : ActiveProfile, PendingProfile, ExpiredProfile, SuspendedProfile, CancelledProfile
    $recdate = date("Y-m-d H:i:s");
    DB_query("INSERT INTO {$_TABLES['paypal_recurrent']} SET profileid='{$resArray['PROFILEID']}', recdate='{$recdate}', status ='{$resArray['PROFILESTATUS']}', user_id = '{$_USER['uid']}', product_id = '{$_SESSION['item_id']}', group_id = '{$_SESSION["group_id"]}' ");
    $display .= "<p>{$LANG_PAYPAL_1['recurrent_has_been_set']} {$LANG_PAYPAL_1['will_pay']} <span style=\"border: 1px solid #DDD; background:#EEE; padding:5px;\">{$_SESSION["currencyCodeType"]} {$_SESSION["BILLINGAMT"]}</span> {$LANG_PAYPAL_1['every']} <span style=\"border: 1px solid #DDD; background:#EEE; padding:5px;\">{$_SESSION["BILLINGFREQUENCY"]} {$_SESSION["BILLINGPERIOD"]}</span></p>";
    if ($finalPaymentAmount = 0) {
        PAYPAL_addToGroup($_SESSION["group_id"], $_USER['uid']);
    }
} else {
    //Display a user friendly Error on the page using any of the following error information returned by PayPal
    $ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
    $ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
    $ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
    $ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
    $display .= "<p>GetExpressCheckoutDetails API call failed.";
    $display .= "</p><p>Detailed Error Message: " . $ErrorLongMsg;
    $display .= "</p><p>Short Error Message: " . $ErrorShortMsg;
    $display .= "</p><p>Error Code: " . $ErrorCode;
    $display .= "</p><p>Error Severity Code: " . $ErrorSeverityCode . '</p>';
}
$display .= PAYPAL_siteFooter();
COM_output($display);
 /**
  * Add a record of the purchase to the DB
  *
  * @param array $products Product Id(s) of Product(s) purchased
  * @param array $quantity Quantity of products purchases
  * @param array $paypal_data IPN POST variables
  * @todo implemente physical item vs. download, reflected in 'status'
  */
 function handlePurchase($products, $quantity, $paypal_data, $product_name)
 {
     global $_TABLES, $_CONF, $_PAY_CONF, $LANG_PAYPAL_EMAIL;
     // initialize file and names arrays
     $files = array();
     $names = array();
     $oldids = $products;
     $products = PAYPAL_realId($products);
     // for each item purchased, record purchase in purchase table
     for ($i = 0; $i < count($products); $i++) {
         if (DEBUG) {
             COM_errorLog('PAYPAL-IPN: Product id:' . $products[$i]);
         }
         // grab relevant product data from product table to insert into purchase table.
         $sql = "SELECT * FROM {$_TABLES['paypal_products']} " . "WHERE id = '{$products[$i]}'";
         $res = DB_query($sql);
         $A = DB_fetchArray($res);
         if (DEBUG) {
             COM_errorLog('PAYPAL-IPN: Type: ' . $A['type']);
         }
         if ($A['download'] > 0) {
             $files[] = $_PAY_CONF['download_path'] . $A['file'];
         }
         //TODO + attribute name
         // Set quantity to one if empty
         if ($quantity[$i] == '') {
             $quantity[$i] = 1;
         }
         $names[] = $product_name[$i] . ' x ' . $quantity[$i];
         // Do record anonymous users in purchase table
         //TODO record product name + product_id with attribute
         if (is_numeric((int) $paypal_data['custom']) && (int) $paypal_data['custom'] > 0) {
             // Add the purchase to the paypal purchase table
             $sql = "INSERT INTO {$_TABLES['paypal_purchases']} SET product_id = '{$products[$i]}', " . "quantity = '{$quantity[$i]}', user_id = '{$paypal_data['custom']}', " . "txn_id = '{$paypal_data['txn_id']}', " . 'purchase_date = NOW(), status = \'complete\'';
             /**
              * @todo implemente physical item vs. download, reflected in 'status'
              */
             // if physical item (aka, must be shipped) status = 'pending', otherwise 'complete'
             //if ( $physical == 1 ) {
             //    $sql .= ", status = 'pending'";
             //} else {
             //    $sql .= ", status = 'complete'";
             //}
             // add an expiration date if appropriate
             if (is_numeric($A['expiration']) && $A['type'] == 'product') {
                 $sql .= ", expiration = DATE_ADD(NOW(), INTERVAL {$A['expiration']} DAY)";
             }
             if (DEBUG) {
                 COM_errorLog('PAYPAL-IPN: ' . $sql);
             }
             DB_query($sql);
             if (DEBUG) {
                 COM_errorLog('PAYPAL-IPN: Purchase recorded');
             }
         }
         // stock movement
         $stock_id = PAYPAL_getStockId($oldids[$i]);
         $qty = $quantity[$i];
         PAYPAL_stockMovement($stock_id, $oldids[$i], -$qty);
     }
     // Update user details if empty user_id, user_name, user_contact, user_proid, user_street1, user_street2, user_postal, user_city, user_country, user_phone1, user_phone2, user_fax, status
     $fields = array('user_name' => $paypal_data['address_name'], 'user_contact' => $paypal_data['first_name'] . ' ' . $paypal_data['last_name'], 'user_street1' => $paypal_data['address_street'], 'user_postal' => $paypal_data['address_zip'], 'user_city' => $paypal_data['address_city'], 'user_country' => $paypal_data['address_country']);
     if (is_numeric((int) $paypal_data['custom']) && (int) $paypal_data['custom'] != 1) {
         PAYPAL_updateUserDetails((int) $paypal_data['custom'], $fields, true);
     }
     // Send the purchaser a confirmation email (if set to do so in config)
     if (is_numeric((int) $paypal_data['custom']) && (int) $paypal_data['custom'] != 1 && $_PAY_CONF['purchase_email_user'] || (!is_numeric($paypal_data['custom']) || (int) $paypal_data['custom'] == 1) && $_PAY_CONF['purchase_email_anon']) {
         // setup templates
         $message = new Template($_CONF['path'] . 'plugins/paypal/templates');
         $message->set_file(array('subject' => 'purchase_email_subject.txt', 'message' => 'purchase_email_message.txt'));
         // site variables
         $message->set_var('site_url', $_CONF['site_url']);
         $message->set_var('site_name', $_CONF['site_name']);
         //Email subject
         $message->set_var('purchase_receipt', $LANG_PAYPAL_EMAIL['purchase_receipt']);
         // list of product names
         for ($i = 0; $i < count($products); $i++) {
             $li_products .= '<li>' . $names[$i];
         }
         $message->set_var('products', $li_products);
         //Email messages
         $message->set_var('thank_you', $LANG_PAYPAL_EMAIL['thank_you']);
         $message->set_var('thanks', $LANG_PAYPAL_EMAIL['thanks']);
         // paypal details
         $message->set_var('payment_gross', $paypal_data['payment_gross']);
         $message->set_var('tax', $paypal_data['tax']);
         $message->set_var('shipping', $paypal_data['mc_shipping']);
         $message->set_var('handling', $paypal_data['mc_handling']);
         $message->set_var('payment_date', $paypal_data['payment_date']);
         $message->set_var('payer_email', $paypal_data['payer_email']);
         $message->set_var('first_name', $paypal_data['first_name']);
         $message->set_var('last_name', $paypal_data['last_name']);
         $subject = trim($message->parse('output', 'subject'));
         // if specified to mail attachment, do so, otherwise skip attachment
         if ((is_numeric((int) $paypal_data['custom']) && (int) $paypal_data['custom'] != 1 && $_PAY_CONF['purchase_email_user_attach'] || (!is_numeric((int) $paypal_data['custom']) || (int) $paypal_data['custom'] == 1) && $_PAY_CONF['purchase_email_anon_attach']) && count($files) > 0) {
             $message->set_var('attached_files', $LANG_PAYPAL_EMAIL['attached_files']);
             $text = $message->parse('output', 'message');
             paypal_mailAttachment($paypal_data['payer_email'], $subject, $text, $files, $_PAY_CONF['receiverEmailAddr']);
         } else {
             if (count($files) > 0) {
                 $message->set_var('attached_files', $LANG_PAYPAL_EMAIL['download_files']);
             } else {
                 $message->set_var('attached_files', '');
             }
             $text = $message->parse('output', 'message');
             COM_mail($paypal_data['payer_email'], $subject, $text, $_PAY_CONF['receiverEmailAddr'], true);
         }
         if (DEBUG) {
             COM_errorLog('PAYPAL-IPN: Email was sent');
         }
     }
     //Send email to receiver
     COM_mail($_PAY_CONF['receiverEmailAddr'], $subject, $subject . ' >> ' . $text, $_PAY_CONF['receiverEmailAddr'], true);
     //Subscription
     if ($A['type'] == 'subscription') {
         //add subscription to db
         PAYPAL_addsubscription($A, $paypal_data);
         if (DEBUG) {
             COM_errorLog('PAYPAL-IPN: Subscription recorded');
         }
         //add  user to group
         if ($A['add_to_group'] > 1 && (int) $paypal_data['custom'] > 1) {
             PAYPAL_addToGroup($A['add_to_group'], $paypal_data['custom']);
             if (DEBUG) {
                 COM_errorLog('PAYPAL-IPN: User with UID ' . $paypal_data['custom'] . ' added to group ID ' . $A['add_to_group']);
             }
         }
     }
 }
         $sql = "INSERT INTO {$_TABLES['paypal_subscriptions']} SET {$sql} ";
     }
     DB_query($sql);
     if (DB_error()) {
         $msg = $LANG_PAYPAL_1['save_fail'];
     } elseif ($_REQUEST['id'] == 0) {
         $msg = $LANG_PAYPAL_1['subscription_label'] . ' >> ' . $LANG_PAYPAL_1['save_success'];
         //add user to group
         if ($_POST['notification'] != '3') {
             PAYPAL_addToGroup($_REQUEST['add_to_group'], $_REQUEST['user_id']);
         }
     } else {
         $msg = $LANG_PAYPAL_1['subscription_label'] . ' ' . $_REQUEST['id'] . ' >> ' . $LANG_PAYPAL_1['save_success'];
         //add user to group
         if ($_POST['notification'] != '3') {
             PAYPAL_addToGroup($_REQUEST['add_to_group'], $_REQUEST['user_id']);
         }
     }
     // save complete, return to product list
     echo COM_refresh($_CONF['site_url'] . "/admin/plugins/paypal/subscriptions.php?msg={$msg}");
     exit;
     break;
 case 'delete':
     DB_delete($_TABLES['paypal_subscriptions'], 'id', $_REQUEST['id']);
     if (DB_affectedRows('') == 1) {
         $msg = $LANG_PAYPAL_1['deletion_succes'];
         //remove user from group
         PAYPAL_removeFromGroup($_REQUEST['add_to_group'], $_REQUEST['user_id']);
     } else {
         $msg = $LANG_PAYPAL_1['deletion_fail'];
     }
         $sql .= ", expiration = DATE_ADD(NOW(), INTERVAL {$product['expiration']} DAY)";
     }
     $sql .= " WHERE txn_id = '{$ipn['txn_id']}' AND product_id = '{$ipn['item_number']}'";
     if ($_PAY_CONF['debug']) {
         COM_errorLog($sql);
     }
     DB_query($sql);
     //Subscription
     if ($product['type'] == 'subscription') {
         //add subscription to db
         PAYPAL_addsubscription($product, $ipn);
         if ($_PAY_CONF['debug']) {
             COM_errorLog('Subscription recorded');
         }
         //add  user to group
         $product['add_to_group'] > 1 ? PAYPAL_addToGroup($product['add_to_group'], $ipn['custom']) : '';
     }
     // stock movement
     $stock_id = PAYPAL_getStockId($ipn['item_number']);
     $qty = $ipn['quantity1'];
     PAYPAL_stockMovement($stock_id, $ipn['item_number'], -$qty);
 }
 //Update IPN
 $ipn['payment_status'] = 'complete';
 $ipn['payment_date'] = date('H:i:s M d, Y T');
 //13:49:40 Jul 06, 2011 PDT
 $sql = "UPDATE {$_TABLES['paypal_ipnlog']} SET ipn_data='" . serialize($ipn) . "' " . "WHERE txn_id = '{$_REQUEST['txn_id']}'";
 DB_query($sql);
 //update purchase
 $sql = "UPDATE {$_TABLES['paypal_purchases']} SET status='complete' " . " WHERE txn_id = '{$_REQUEST['txn_id']}'";
 DB_query($sql);