function xtc_address_format($address_format_id, $address, $html, $boln, $eoln)
{
    $address_format_query = xtc_db_query("select address_format as format from " . TABLE_ADDRESS_FORMAT . " where address_format_id = '" . xtc_db_input((int) $address_format_id) . "'");
    $address_format = xtc_db_fetch_array($address_format_query);
    $company = addslashes($address['company']);
    $firstname = addslashes($address['firstname']);
    $lastname = addslashes($address['lastname']);
    $street = addslashes($address['street_address']);
    $suburb = addslashes($address['suburb']);
    $city = addslashes($address['city']);
    $state = addslashes($address['state']);
    $country_id = $address['country_id'];
    $zone_id = $address['zone_id'];
    $postcode = addslashes($address['postcode']);
    $zip = $postcode;
    $country = xtc_get_country_name($country_id);
    $state = xtc_get_zone_code($country_id, $zone_id, $state);
    if ($html) {
        // HTML Mode
        $HR = '<hr />';
        $hr = '<hr />';
        if ($boln == '' && $eoln == "\n") {
            // Values not specified, use rational defaults
            $CR = '<br />';
            $cr = '<br />';
            $eoln = $cr;
        } else {
            // Use values supplied
            $CR = $eoln . $boln;
            $cr = $CR;
        }
    } else {
        // Text Mode
        $CR = $eoln;
        $cr = $CR;
        $HR = '----------------------------------------';
        $hr = '----------------------------------------';
    }
    $statecomma = '';
    $streets = $street;
    if ($suburb != '') {
        $streets = $street . $cr . $suburb;
    }
    if ($firstname == '') {
        $firstname = addslashes($address['name']);
    }
    if ($country == '') {
        $country = addslashes($address['country']);
    }
    if ($state != '') {
        $statecomma = $state . ', ';
    }
    $fmt = $address_format['format'];
    eval("\$address = \"{$fmt}\";");
    if (ACCOUNT_COMPANY == 'true' && xtc_not_null($company)) {
        $address = $company . $cr . $address;
    }
    $address = stripslashes($address);
    return $address;
}
function xtc_address_summary($customers_id, $address_id)
{
    $customers_id = xtc_db_prepare_input($customers_id);
    $address_id = xtc_db_prepare_input($address_id);
    $address_query = xtc_db_query("select ab.entry_street_address, ab.entry_suburb, ab.entry_postcode, ab.entry_city, ab.entry_state, ab.entry_country_id, ab.entry_zone_id, c.countries_name, c.address_format_id from " . TABLE_ADDRESS_BOOK . " ab, " . TABLE_COUNTRIES . " c where ab.address_book_id = '" . xtc_db_input((int) $address_id) . "' and ab.customers_id = '" . xtc_db_input((int) $customers_id) . "' and ab.entry_country_id = c.countries_id");
    $address = xtc_db_fetch_array($address_query);
    $street_address = $address['entry_street_address'];
    $suburb = $address['entry_suburb'];
    $postcode = $address['entry_postcode'];
    $city = $address['entry_city'];
    $state = xtc_get_zone_code($address['entry_country_id'], $address['entry_zone_id'], $address['entry_state']);
    $country = $address['countries_name'];
    $address_format_query = xtc_db_query("select address_summary from " . TABLE_ADDRESS_FORMAT . " where address_format_id = '" . (int) $address['address_format_id'] . "'");
    $address_format = xtc_db_fetch_array($address_format_query);
    //    eval("\$address = \"{$address_format['address_summary']}\";");
    $address_summary = $address_format['address_summary'];
    eval("\$address = \"{$address_summary}\";");
    return $address;
}
 function complete_cart($order_exists = true)
 {
     global $insert_id;
     // check
     $check_query = xtc_db_query("SELECT * \n                                   FROM " . TABLE_PAYPAL_PAYMENT . "\n                                  WHERE payment_id = '" . xtc_db_input($_SESSION['paypal']['paymentId']) . "'");
     if (xtc_db_num_rows($check_query) > 0) {
         $status_id = $this->order_status_tmp;
         if ($status_id < 0) {
             $check_query = xtc_db_query("SELECT orders_status\n                                         FROM " . TABLE_ORDERS . " \n                                        WHERE orders_id = '" . (int) $insert_id . "'");
             $check = xtc_db_fetch_array($check_query);
             $status_id = $check['orders_status'];
         }
         $this->update_order('duplicate call, cancel', $status_id, $insert_id);
         return;
     }
     // auth
     $apiContext = $this->apiContext();
     try {
         // Get the payment Object by passing paymentId
         $payment = Payment::get($_SESSION['paypal']['paymentId'], $apiContext);
     } catch (Exception $ex) {
         $this->LoggingManager->log(print_r($ex, true), 'DEBUG');
         $this->remove_order($insert_id);
         unset($_SESSION['paypal']);
         unset($_SESSION['tmp_oID']);
         xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL'));
     }
     // set order
     $order = new order($insert_id);
     $patches_array = array();
     $patchRequest = new PatchRequest();
     $payment_address = new Address();
     $payment_address->setLine1($this->encode_utf8($order->billing['street_address']))->setCity($this->encode_utf8($order->billing['city']))->setState($this->encode_utf8($order->billing['state'] != '' ? xtc_get_zone_code($order->billing['country_id'], $order->billing['zone_id'], $order->billing['state']) : ''))->setPostalCode($this->encode_utf8($order->billing['postcode']))->setCountryCode($this->encode_utf8(isset($order->billing['country_iso_2']) ? $order->billing['country_iso_2'] : $order->billing['country']['iso_code_2']));
     if ($order->billing['suburb'] != '') {
         $payment_address->setLine2($this->encode_utf8($order->billing['suburb']));
     }
     $patch_payment = new Patch();
     $patch_payment->setOp('add')->setPath('/potential_payer_info/billing_address')->setValue($payment_address);
     $patches_array[] = $patch_payment;
     // set address
     $shipping_address = new ShippingAddress();
     $shipping_address->setRecipientName($this->encode_utf8($order->delivery['firstname'] . ' ' . $order->delivery['lastname']))->setLine1($this->encode_utf8($order->delivery['street_address']))->setCity($this->encode_utf8($order->delivery['city']))->setCountryCode($this->encode_utf8(isset($order->delivery['country_iso_2']) ? $order->delivery['country_iso_2'] : $order->delivery['country']['iso_code_2']))->setPostalCode($this->encode_utf8($order->delivery['postcode']))->setState($this->encode_utf8($order->delivery['state'] != '' ? xtc_get_zone_code($order->delivery['country_id'], $order->delivery['zone_id'], $order->delivery['state']) : ''));
     if ($order->delivery['suburb'] != '') {
         $shipping_address->setLine2($this->encode_utf8($order->delivery['suburb']));
     }
     $patch_shipping = new Patch();
     $patch_shipping->setOp('add')->setPath('/transactions/0/item_list/shipping_address')->setValue($shipping_address);
     $patches_array[] = $patch_shipping;
     $patch_invoice = new Patch();
     $patch_invoice->setOp('replace')->setPath('/transactions/0/invoice_number')->setValue($this->get_config('PAYPAL_CONFIG_INVOICE_PREFIX') . $insert_id);
     $patches_array[] = $patch_invoice;
     // set details
     $this->details = new Details();
     // set amount
     $this->amount = new Amount();
     // set totals
     $this->get_totals($order->totals);
     $this->amount->setCurrency($order->info['currency'])->setDetails($this->details);
     $patch_amount = new Patch();
     $patch_amount->setOp('replace')->setPath('/transactions/0/amount')->setValue($this->amount);
     $patches_array[] = $patch_amount;
     // set ItemList
     if ($this->get_config('PAYPAL_ADD_CART_DETAILS') == '0' || $this->check_discount() === true) {
         $item = array();
         $item[0] = new Item();
         $item[0]->setName($this->encode_utf8(MODULE_PAYMENT_PAYPAL_TEXT_ORDER))->setCurrency($order->info['currency'])->setQuantity(1)->setPrice($this->details->getSubtotal());
     } else {
         for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
             $item[$i] = new Item();
             $item[$i]->setName($this->encode_utf8($order->products[$i]['name']))->setCurrency($order->info['currency'])->setQuantity($order->products[$i]['qty'])->setPrice($order->products[$i]['price'])->setSku($order->products[$i]['model'] != '' ? $order->products[$i]['model'] : $order->products[$i]['id']);
         }
     }
     $patch_items = new Patch();
     $patch_items->setOp('replace')->setPath('/transactions/0/item_list/items')->setValue($item);
     $patches_array[] = $patch_items;
     $patchRequest->setPatches($patches_array);
     try {
         // update payment
         $payment->update($patchRequest, $apiContext);
     } catch (Exception $ex) {
         $this->LoggingManager->log(print_r($ex, true), 'DEBUG');
         if ($order_exists === false) {
             unset($_SESSION['paypal']);
             xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, 'payment_error=' . $this->code, 'SSL'));
         }
         $this->remove_order($insert_id);
         unset($_SESSION['paypal']);
         unset($_SESSION['tmp_oID']);
         xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL'));
     }
     $payment = Payment::get($_SESSION['paypal']['paymentId'], $apiContext);
     // PaymentExecution
     $execution = new PaymentExecution();
     $execution->setPayerId($_SESSION['paypal']['PayerID']);
     try {
         // Execute the payment
         $payment->execute($execution, $apiContext);
     } catch (Exception $ex) {
         $this->LoggingManager->log(print_r($ex, true), 'DEBUG');
         $this->remove_order($insert_id);
         unset($_SESSION['paypal']);
         unset($_SESSION['tmp_oID']);
         xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL'));
     }
     // capture
     if (($this->transaction_type == 'order' || $this->transaction_type == 'authorize') && $this->get_config('PAYPAL_CAPTURE_MANUELL') == '0') {
         $this->capture_payment($payment);
     }
     $sql_data_array = array('orders_id' => $insert_id, 'payment_id' => $_SESSION['paypal']['paymentId'], 'payer_id' => $_SESSION['paypal']['PayerID']);
     xtc_db_perform(TABLE_PAYPAL_PAYMENT, $sql_data_array);
     try {
         // Get the payment Object by passing paymentId
         $payment = Payment::get($_SESSION['paypal']['paymentId'], $apiContext);
     } catch (Exception $ex) {
         $this->LoggingManager->log(print_r($ex, true), 'DEBUG');
         $this->remove_order($insert_id);
         unset($_SESSION['paypal']);
         unset($_SESSION['tmp_oID']);
         xtc_redirect(xtc_href_link(FILENAME_SHOPPING_CART, 'payment_error=' . $this->code, 'NONSSL'));
     }
     $status = $this->get_orders_status($payment);
     if ($status['status_id'] < 0) {
         $check_query = xtc_db_query("SELECT orders_status\n                                     FROM " . TABLE_ORDERS . " \n                                    WHERE orders_id = '" . (int) $insert_id . "'");
         $check = xtc_db_fetch_array($check_query);
         $status['status_id'] = $check['orders_status'];
     }
     $this->update_order($status['comment'], $status['status_id'], $insert_id);
 }
     xtc_db_query($sql);
     // Get Sum of payment (Could have changed since last selects);
     $sql = "\n        SELECT sum(affiliate_payment) as affiliate_payment\n          FROM " . TABLE_AFFILIATE_SALES . " \n          WHERE affiliate_id='" . $affiliate_payment['affiliate_id'] . "' and  affiliate_billing_status=99 \n        ";
     $affiliate_billing_query = xtc_db_query($sql);
     $affiliate_billing = xtc_db_fetch_array($affiliate_billing_query);
     // Get affiliate Informations
     $sql = "\n        SELECT a.*, c.countries_id, c.countries_name, c.countries_iso_code_2, c.countries_iso_code_3, c.address_format_id \n          from " . TABLE_AFFILIATE . " a \n          left join " . TABLE_ZONES . " z on (a.affiliate_zone_id  = z.zone_id) \n          left join " . TABLE_COUNTRIES . " c on (a.affiliate_country_id = c.countries_id)\n          WHERE affiliate_id = '" . $affiliate_payment['affiliate_id'] . "' \n        ";
     $affiliate_query = xtc_db_query($sql);
     $affiliate = xtc_db_fetch_array($affiliate_query);
     // Get need tax informations for the affiliate
     $affiliate_tax_rate = xtc_get_affiliate_tax_rate(AFFILIATE_TAX_ID, $affiliate['affiliate_country_id'], $affiliate['affiliate_zone_id']);
     $affiliate_tax = xtc_round($affiliate_billing['affiliate_payment'] * $affiliate_tax_rate / 100, 2);
     // Netto-Provision
     $affiliate_payment_total = $affiliate_billing['affiliate_payment'];
     // Bill the order
     $affiliate['affiliate_state'] = xtc_get_zone_code($affiliate['affiliate_country_id'], $affiliate['affiliate_zone_id'], $affiliate['affiliate_state']);
     $sql_data_array = array('affiliate_id' => $affiliate_payment['affiliate_id'], 'affiliate_payment' => $affiliate_billing['affiliate_payment'] - $affiliate_tax, 'affiliate_payment_tax' => $affiliate_tax, 'affiliate_payment_total' => $affiliate_payment_total, 'affiliate_payment_date' => 'now()', 'affiliate_payment_status' => '0', 'affiliate_firstname' => $affiliate['affiliate_firstname'], 'affiliate_lastname' => $affiliate['affiliate_lastname'], 'affiliate_street_address' => $affiliate['affiliate_street_address'], 'affiliate_suburb' => $affiliate['affiliate_suburb'], 'affiliate_city' => $affiliate['affiliate_city'], 'affiliate_country' => $affiliate['countries_name'], 'affiliate_postcode' => $affiliate['affiliate_postcode'], 'affiliate_company' => $affiliate['affiliate_company'], 'affiliate_state' => $affiliate['affiliate_state'], 'affiliate_address_format_id' => $affiliate['address_format_id']);
     xtc_db_perform(TABLE_AFFILIATE_PAYMENT, $sql_data_array);
     $insert_id = xtc_db_insert_id();
     // Set the Sales to Final State
     xtc_db_query("update " . TABLE_AFFILIATE_SALES . " set affiliate_payment_id = '" . $insert_id . "', affiliate_billing_status = 1, affiliate_payment_date = now() where affiliate_id = '" . $affiliate_payment['affiliate_id'] . "' and affiliate_billing_status = 99");
     // Notify Affiliate
     if (AFFILIATE_NOTIFY_AFTER_BILLING == 'true') {
         $check_status_query = xtc_db_query("select af.affiliate_email_address, ap.affiliate_lastname, ap.affiliate_firstname, ap.affiliate_payment_status, ap.affiliate_payment_date, ap.affiliate_payment_date from " . TABLE_AFFILIATE_PAYMENT . " ap, " . TABLE_AFFILIATE . " af where affiliate_payment_id  = '" . $insert_id . "' and af.affiliate_id = ap.affiliate_id ");
         $check_status = xtc_db_fetch_array($check_status_query);
         $email = STORE_NAME . "\n" . EMAIL_SEPARATOR . "\n" . EMAIL_TEXT_AFFILIATE_PAYMENT_NUMBER . ' ' . $insert_id . "\n" . EMAIL_TEXT_INVOICE_URL . ' ' . xtc_catalog_href_link(FILENAME_CATALOG_AFFILIATE_PAYMENT_INFO, 'payment_id=' . $insert_id, 'SSL') . "\n" . EMAIL_TEXT_PAYMENT_BILLED . ' ' . xtc_date_long($check_status['affiliate_payment_date']) . "\n\n" . EMAIL_TEXT_NEW_PAYMENT;
         xtc_php_mail(AFFILIATE_EMAIL_ADDRESS, EMAIL_SUPPORT_NAME, $check_status['affiliate_email_address'], $check_status['affiliate_firstname'] . ' ' . $check_status['affiliate_lastname'], '', EMAIL_SUPPORT_REPLY_ADDRESS, EMAIL_SUPPORT_REPLY_ADDRESS_NAME, '', '', EMAIL_TEXT_SUBJECT, nl2br($email), $email);
     }
 }
 $messageStack->add_session(SUCCESS_BILLING, 'success');
 xtc_redirect(xtc_href_link(FILENAME_AFFILIATE_PAYMENT, xtc_get_all_get_params(array('action')) . 'action=edit'));