/**	
 * Starts transaction process for specified transaction
 * 
 * @param int $localTranID				- starting transaction database ID
 * @param bool $recurring				- indicates whether transaction recurring or not
 * @param int $recurringDays			- if $recurring true, then this value specifies
 * 										  subscription days
 * 
 * @return bool 						- true if start is successful, false otherwise
 * 
 * 
 */
function moduleStartTransaction($localTranID, $recurring = false, $recurringDays = 0)
{
    global $providerConf;
    global $checkoutURL;
    global $memberID;
    // defined in checkout.inc.php
    global $cryptKey;
    global $currency_code;
    global $prof;
    global $date_format;
    // validate arguments
    $localTranID = (int) $localTranID;
    $recurringDays = (int) $recurringDays;
    $tranRes = db_res("SELECT DATE_FORMAT(`Date`,  '{$date_format}' ) AS 'Date', `Amount`, `Currency`, `Status`, `Data`, `Description` FROM `Transactions`\r\n\t\t\t\t\t\t\tWHERE `ID` = {$localTranID}\r\n\t\t\t\t\t\t\tAND `Status` = 'pending'\r\n\t\t\t\t\t\t\tAND `IDProvider` = {$providerConf['ID']}");
    if (!$tranRes || mysql_num_rows($tranRes) == 0) {
        return false;
    }
    $tranArr = mysql_fetch_assoc($tranRes);
    $tranData = transStringToData($tranArr['Data']);
    $actionURL = 'https://www.2checkout.com/2co/buyer/purchase';
    $formData = array();
    // account ID
    $formData['sid'] = $providerConf['Param_sid'];
    // transaction common data
    $formData['cart_order_id'] = $localTranID;
    $formData['total'] = sprintf("%.2f", (double) $tranArr['Amount']);
    $formData['tran_description'] = $tranArr['Description'];
    $formData['pay_method'] = $providerConf['Param_pay_method'];
    $formData['fixed'] = 'Y';
    // return and redirect
    $returnURL = returnURLByAction($tranData['action'], $tranData['data']);
    $formData['return_url'] = $returnURL;
    // test mode
    if ($providerConf['Mode'] != 'live') {
        $formData['demo'] = 'Y';
    }
    Redirect($actionURL, $formData, 'post', $providerConf['Caption']);
    exit;
}
        $paymentProviders = getPaymentProviders(false);
        ?>
		<tr class=panel>
			<td align="left" nowrap>Order number</td>
			<td align="left" nowrap>Date</td>
			<td align="left" nowrap>Member</td>
			<td align="left" nowrap>Provider</td>
			<td align="center" nowrap>Info</td>
			<td align="right" nowrap>Sum paid, <?php 
        echo $currency_code;
        ?>
</td>
		</tr>
	<?php 
        while ($tr_arr = mysql_fetch_array($tr_res)) {
            $tranDataArray = transStringToData($tr_arr['Data']);
            $tranTypeString = '<b>Type:</b> ' . $tranDataArray['action'];
            $tranDataString = '<b>Description:</b> ' . returnDescByAction($tranDataArray['action'], $tranDataArray['data'], false);
            $tranNoteString = strlen($tr_arr['Note']) ? '<b>Note:</b> ' . $tr_arr['Note'] : '';
            ?>
		<tr class=table>
			<td><?php 
            echo $tr_arr['gtwTransactionID'];
            ?>
</td>
			<td align="left" nowrap><?php 
            echo $tr_arr['Date'];
            ?>
</td>
			<td align="left" nowrap><?php 
            echo "<a href=\"{$site['url']}profile.php?ID={$tr_arr['IDMember']}\">{$tr_arr['IDMember']}</a>";
/**
 * Performs common payment transaction validation
 *
 * @param int $localTranID				- transaction ID
 * @param string $amount				- payment sum, received from the gateway
 * @param string &$errorMessage			- error message when return result is not true
 *
 * @return bool 						- true if configuration is valid, false otherwise
 *
 *
 */
function commonValidateTransaction($localTranID, $amount, &$errorMessage)
{
    global $cryptKey;
    // arguments validation
    $localTranID = (int) $localTranID;
    $tranRes = db_res("SELECT `Data` FROM `Transactions`\r\n\t\t\t\t\t\t\tWHERE `ID` = {$localTranID}");
    if (!$tranRes || mysql_num_rows($tranRes) == 0) {
        $errorMessage = 'Invalid transaction ID';
        return false;
    }
    $tranArr = mysql_fetch_assoc($tranRes);
    $tranData = transStringToData($tranArr['Data']);
    if ($tranData['amount'] != sprintf("%.2f", (double) $amount)) {
        $errorMessage = 'Invalid payment sum';
        return false;
    }
    $res = db_res("SELECT `ID` FROM `Profiles` WHERE `ID` = {$tranData['memberID']}");
    if (!$res) {
        $errorMessage = 'Invalid member ID';
        return false;
    }
    if (crypt($tranData['amount'], $cryptKey) != $tranData['cryptedAmount'] || crypt($tranData['data'], $cryptKey) != $tranData['cryptedData']) {
        $errorMessage = 'Invalid verification data';
        return false;
    }
    return true;
}
/**	
 * Starts transaction process for specified transaction
 * 
 * @param int $localTranID				- starting transaction database ID
 * @param bool $recurring				- indicates whether transaction recurring or not
 * @param int $recurringDays			- if $recurring true, then this value specifies
 * 										  subscription days
 * 
 * @return bool 						- true if start is successful, false otherwise
 * 
 * 
 */
function moduleStartTransaction($localTranID, $recurring = false, $recurringDays = 0)
{
    global $providerConf;
    global $checkoutURL;
    global $memberID;
    // defined in checkout.inc.php
    global $cryptKey;
    global $currency_code;
    global $enable_recurring;
    global $date_format;
    // validate arguments
    $localTranID = (int) $localTranID;
    $recurringDays = (int) $recurringDays;
    $tranRes = db_res("SELECT DATE_FORMAT(`Date`,  '{$date_format}' ) AS 'Date', `Amount`, `Currency`, `Status`, `Data`, `Description` FROM `Transactions`\r\n\t\t\t\t\t\t\tWHERE `ID` = {$localTranID}\r\n\t\t\t\t\t\t\tAND `Status` = 'pending'\r\n\t\t\t\t\t\t\tAND `IDProvider` = {$providerConf['ID']}");
    if (!$tranRes || mysql_num_rows($tranRes) == 0) {
        return false;
    }
    $tranArr = mysql_fetch_assoc($tranRes);
    $tranData = transStringToData($tranArr['Data']);
    if ($providerConf['Mode'] != 'live') {
        $actionURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
    } else {
        $actionURL = 'https://www.paypal.com/cgi-bin/webscr';
    }
    $formData = array();
    // command and recurring parameters
    if ($recurring) {
        $formData['cmd'] = '_xclick-subscriptions';
        $formData['a3'] = sprintf("%.2f", (double) $tranArr['Amount']);
        $formData['p3'] = $recurringDays;
        $formData['t3'] = 'D';
        $formData['src'] = '1';
        // repeat billings unles member cancels subscription
        $formData['sra'] = '1';
        // reattempt on failure
    } else {
        $formData['cmd'] = '_xclick';
        $formData['amount'] = sprintf("%.2f", (double) $tranArr['Amount']);
    }
    // business (merchant ID)
    if ($providerConf['Mode'] != 'live') {
        $formData['business'] = $providerConf['Param_test_business'];
    } else {
        $formData['business'] = $providerConf['Param_business'];
    }
    // transaction common data
    $formData['item_name'] = $tranArr['Description'];
    $formData['item_number'] = $localTranID;
    $formData['currency_code'] = $currency_code;
    $formData['no_note'] = $providerConf['Param_no_note'] ? '1' : '0';
    $formData['no_shipping'] = '1';
    $formData['custom'] = md5($tranArr['Date'] . $tranArr['Data'] . $cryptKey);
    // return and redirect
    switch ($providerConf['Param_process_type']) {
        case 'Direct':
            $formData['return'] = $checkoutURL;
            $formData['rm'] = '2';
            break;
        case 'IPN':
            $returnURL = returnURLByAction($tranData['action'], $tranData['data']);
            $formData['return'] = $returnURL;
            $formData['notify_url'] = $checkoutURL;
            $formData['rm'] = '1';
            break;
        case 'PDT':
            $formData['return'] = $checkoutURL;
            $formData['rm'] = '2';
            break;
    }
    Redirect($actionURL, $formData, 'post', $providerConf['Caption']);
    exit;
}
/**	
 * Performs server side call payment processing
 * 
 * @param bool $subscribe				- indicates if payment is subcriptional payment
 * @param int $newTrandID				- if payment subscriptional, then $newTrandID specfies
 * 										  new transaction ID created by script
 * 
 * @return bool 						- true if payment is successful, false otherwise
 * 
 * 
 */
function moduleAcceptPayment($subscribe, $newTrandID = 0)
{
    global $providerConf;
    global $date_format;
    $errorMessage = '';
    if ($providerConf['Debug']) {
        writeDebugLog('Payment event', 'Payment start', false);
    }
    if ($providerConf['Param_implementation'] == 'AIM') {
        if (!isset($_POST['send_data']) || !isset($_POST['auth_card_num']) || !isset($_POST['auth_tran_id'])) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $transactionData = $_POST;
        if (!validateCheckoutData($transactionData)) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $localTranID = (int) $transactionData['auth_tran_id'];
        $tranRes = db_res("SELECT DATE_FORMAT(`Date`,  '{$date_format}' ) AS 'Date', `Amount`, `Currency`, `Status`, `Data`, `Description` FROM `Transactions`\r\n\t\t\t\t\t\t\t\tWHERE `ID` = {$localTranID}\r\n\t\t\t\t\t\t\t\tAND `Status` = 'pending'\r\n\t\t\t\t\t\t\t\tAND `IDProvider` = {$providerConf['ID']}");
        if (!$tranRes || mysql_num_rows($tranRes) == 0) {
            return false;
        }
        $tranArr = mysql_fetch_assoc($tranRes);
        $tranData = transStringToData($tranArr['Data']);
        $postURL = 'https://secure.authorize.net/gateway/transact.dll';
        $postParameters = "x_login={$providerConf['Param_x_login']}";
        $postParameters .= "&x_tran_key={$providerConf['Param_x_tran_key']}";
        $postParameters .= "&x_version=3.1";
        $postParameters .= "&x_method=CC";
        $postParameters .= "&x_type=AUTH_CAPTURE";
        $postParameters .= "&x_amount=" . sprintf("%.2f", (double) $tranArr['Amount']);
        $postParameters .= "&x_invoice_num={$localTranID}";
        $postParameters .= "&x_description={$tranArr['Description']}";
        $postParameters .= "&x_relay_response=FALSE";
        $postParameters .= "&x_email_customer=FALSE";
        $postParameters .= "&x_delim_data=TRUE";
        $postParameters .= "&x_delim_char={$providerConf['Param_x_delim_char']}";
        $postParameters .= "&x_encap_char={$providerConf['Param_x_encap_char']}";
        $postParameters .= "&x_card_num={$transactionData['auth_card_num']}";
        $postParameters .= "&x_exp_date={$transactionData['auth_expire_month']}-{$transactionData['auth_expire_year']}";
        $postParameters .= "&x_cust_id={$tranData['memberID']}";
        $postParameters .= "&x_test_request=" . ($providerConf['Mode'] == 'live' ? 'FALSE' : 'TRUE');
        $response = sendCurlRequest($postURL, $postParameters);
        if ($providerConf['Debug']) {
            writeDebugLog('AIM request response', $response, false);
        }
        $responseArr = explode($providerConf['Param_x_delim_char'], $response);
        $encapChar = $providerConf['Param_x_encap_char'];
        if ($encapChar == '\'' || $encapChar == '\\') {
            $encapChar = '\\' . $encapChar;
        }
        array_walk($responseArr, create_function('&$arg', "\$arg = trim(\$arg, '{$encapChar}');"));
        $transactionData = $responseArr;
        $res = moduleValidateTransaction($transactionData, $errorMessage);
        $localTranID = (int) $transactionData[7];
        if ($res != 2) {
            finishTransaction($localTranID, $transactionData[6], $res == 1);
        }
        if ($res == 1) {
            $purchaseRes = purchaseTransaction($localTranID, $res);
            if (!$purchaseRes) {
                $errorMessage = 'Purchase failed';
                $res = 0;
            }
        }
        processValidationResult($res, $errorMessage, $localTranID);
        return $res == 1;
    } elseif ($providerConf['Param_implementation'] == 'SIM') {
        if (!isset($_POST['x_response_code']) || !isset($_POST['x_invoice_num'])) {
            PrintErrorPage(_t('_no data given'));
            return false;
        }
        $transactionData = $_POST;
        $res = moduleValidateTransaction($transactionData, $errorMessage);
        $localTranID = (int) $transactionData['x_invoice_num'];
        if ($res != 2) {
            finishTransaction($localTranID, $transactionData['x_trans_id'], $res == 1);
        }
        if ($res == 1) {
            $purchaseRes = purchaseTransaction($localTranID, $res);
            if (!$purchaseRes) {
                $errorMessage = 'Purchase failed';
                $res = 0;
            }
        }
        processValidationResult($res, $errorMessage, $localTranID);
        return $res == 1;
    }
    return false;
}
/**	
 * Starts transaction process for specified transaction
 * 
 * @param int $localTranID				- starting transaction database ID
 * @param bool $recurring				- indicates whether transaction recurring or not
 * @param int $recurringDays			- if $recurring true, then this value specifies
 * 										  subscription days
 * 
 * @return bool 						- true if start is successful, false otherwise
 * 
 * 
 */
function moduleStartTransaction($localTranID, $recurring = false, $recurringDays = 0)
{
    global $providerConf;
    global $checkoutURL;
    global $memberID;
    // defined in checkout.inc.php
    global $cryptKey;
    global $currency_code;
    global $date_format;
    // validate arguments
    $localTranID = (int) $localTranID;
    $recurringDays = (int) $recurringDays;
    $tranRes = db_res("SELECT DATE_FORMAT(`Date`,  '{$date_format}' ) AS 'Date', `Amount`, `Currency`, `Status`, `Data`, `Description` FROM `Transactions`\r\n\t\t\t\t\t\t\tWHERE `ID` = {$localTranID}\r\n\t\t\t\t\t\t\tAND `Status` = 'pending'\r\n\t\t\t\t\t\t\tAND `IDProvider` = {$providerConf['ID']}");
    if (!$tranRes || mysql_num_rows($tranRes) == 0) {
        return false;
    }
    $tranArr = mysql_fetch_assoc($tranRes);
    $tranData = transStringToData($tranArr['Data']);
    $actionURL = 'https://bill.ccbill.com/jpost/signup.cgi';
    $formData = array();
    // account ID
    $formData['clientAccnum'] = $providerConf['Param_client_accnum'];
    $formData['clientSubacc'] = $providerConf['Param_client_subacc'];
    // transaction common data
    $formData['formName'] = $providerConf['Param_form_name'];
    $formData['allowedTypes'] = $providerConf['Param_allowed_types'];
    $formData['subscriptionTypeId'] = $providerConf['Param_subscription_type_id'];
    $formData['productDesc'] = $localTranID;
    $formData['member_id'] = $memberID;
    Redirect($actionURL, $formData, 'post', $providerConf['Caption']);
    exit;
}