/**
  * Prepares and returns necessary data, passed to the payment gateway.
  *
  * @ not all data is defined
  */
 function getConfirmationData($orderId)
 {
     global $application;
     loadCoreFile('aal.class.php');
     $request = new Request();
     $request->setView(CURRENT_REQUEST_URL);
     $request->setAction("UpdatePaymentStatus");
     $request->setKey("asc_oid", $orderId);
     $self_link = $request->getURL("", true);
     $currency_id = modApiFunc("Localization", "whichCurrencySendOrderToPaymentShippingGatewayIn", $orderId, $this->getUid());
     $currency = modApiFunc("Localization", "getCurrencyCodeById", $currency_id);
     $ocntr = modApiFunc("Location", "getCountryCode", modApiFunc("Configuration", "getValue", SYSCONFIG_STORE_OWNER_COUNTRY));
     $bn_code = "PentasoftCorp_Cart_WPS_" . $ocntr;
     $orderInfo = modApiFunc("Checkout", "getOrderInfo", $orderId, $currency_id);
     $discount = $this->export_PRICE_N_A(modApiFunc("Checkout", "getOrderPrice", "DiscountsSum", $currency_id));
     $gc = $this->export_PRICE_N_A(modApiFunc("Checkout", "getOrderPrice", "TotalPrepaidByGC", $currency_id));
     $amount = $this->export_PRICE_N_A(modApiFunc("Checkout", "getOrderPrice", "Subtotal", $currency_id) - $discount - $gc);
     if ($amount < 0) {
         $amount = 0;
     }
     $this->getSettings();
     $confirmationData = array("FormMethod" => "POST", "DataFields" => array("cmd" => "_xclick", "rm" => "2", "business" => $this->Settings["MODULE_EMAIL"], "item_name" => modApiFunc("Configuration", "getValue", SYSCONFIG_STORE_OWNER_NAME), "amount" => number_format($amount, 2, '.', ''), "shipping" => number_format($this->export_PRICE_N_A(modApiFunc("Checkout", "getOrderPrice", "TotalShippingAndHandlingCost", $currency_id)), 2, '.', ''), "tax" => number_format($this->export_PRICE_N_A(modApiFunc("Checkout", "getOrderPrice", "NotIncludedTax", $currency_id)), 2, '.', ''), "currency_code" => $currency, "bn" => $bn_code, "return" => $self_link . "&status=return", "notify_url" => $self_link . "&status=notify", "cancel_return" => $self_link . "&status=cancel"));
     if ($this->Settings['MODULE_CART'] == 1 && $discount == 0) {
         $items = array();
         $n = 1;
         foreach ($orderInfo["Products"] as $productInfo) {
             $items["item_name_" . $n] = prepareHTMLDisplay($productInfo["name"]);
             $items["amount_" . $n] = number_format($productInfo["SalePrice"], 2);
             $items["quantity_" . $n] = $productInfo["qty"];
             foreach ($productInfo["options"] as $i => $option) {
                 if ($i > 1) {
                     $items["os1_" . $n] .= ", " . $option["option_name"] . ": " . $option["option_value"];
                     if (_ml_strlen($items["os1_" . $n]) >= 200) {
                         $items["os1_" . $n] = _ml_substr($items["os1_" . $n], 0, 197) . "...";
                     }
                 } else {
                     $items["on" . $i . "_" . $n] = $option["option_name"];
                     $items["os" . $i . "_" . $n] = $option["option_value"];
                 }
             }
             $n++;
         }
         $confirmationData["DataFields"] = array_merge($confirmationData["DataFields"], $items);
         $confirmationData["DataFields"]["cmd"] = "_cart";
         $confirmationData["DataFields"]["upload"] = "1";
         $confirmationData["DataFields"]["handling_cart"] = $this->export_PRICE_N_A(modApiFunc("Checkout", "getOrderPrice", "TotalShippingAndHandlingCost", $currency_id));
         $confirmationData["DataFields"]["tax_cart"] = $this->export_PRICE_N_A(modApiFunc("Checkout", "getOrderPrice", "NotIncludedTax", $currency_id));
         unset($confirmationData["DataFields"]["shipping"]);
         unset($confirmationData["DataFields"]["tax"]);
     }
     if ($this->Settings['MODULE_BILLING_INFO'] == 1) {
         $billingInfo = new ArrayAccessLayer($orderInfo);
         $billingInfo->setAccessMask("Billing", "attr", AAL_CUSTOM_PARAM, "value");
         if ($confirmationData["DataFields"]["cmd"] == "_xclick") {
             $confirmationData["DataFields"]["cmd"] = "_ext-enter";
             $confirmationData["DataFields"]["redirect_cmd"] = "_xclick";
         }
         $confirmationData["DataFields"]["first_name"] = $billingInfo->getByMask('Firstname');
         $confirmationData["DataFields"]["last_name"] = $billingInfo->getByMask('Lastname');
         $confirmationData["DataFields"]["address1"] = $billingInfo->getByMask('Streetline1');
         $confirmationData["DataFields"]["address2"] = $billingInfo->getByMask('Streetline2');
         $confirmationData["DataFields"]["city"] = $billingInfo->getByMask('City');
         $confirmationData["DataFields"]["state"] = modApiFunc("Location", "getStateCodeByStateName", $billingInfo->getByMask('State'));
         if (!$confirmationData["DataFields"]["state"]) {
             $confirmationData["DataFields"]["state"] = $billingInfo->getByMask('State');
         }
         $confirmationData["DataFields"]["zip"] = $billingInfo->getByMask('Postcode');
         $confirmationData["DataFields"]["country"] = modApiFunc("Location", "getCountryCodeByCountryName", $billingInfo->getByMask('Country'));
         $confirmationData["DataFields"]["email"] = $billingInfo->getByMask('Email');
         if ($billingInfo->getByMask('Phone')) {
             $phone = $billingInfo->getByMask('Phone');
             $phone = preg_replace("/[^0-9]/", "", $phone);
             if (isset($confirmationData["DataFields"]["country"]) && $confirmationData["DataFields"]["country"] == "US") {
                 if (_ml_strlen($phone) == 10) {
                     $confirmationData["DataFields"]["night_phone_c"] = _ml_substr($phone, -4);
                     $phone = _ml_substr($phone, 0, -4);
                     $confirmationData["DataFields"]["night_phone_b"] = _ml_substr($phone, -3);
                     $phone = _ml_substr($phone, 0, -3);
                     $confirmationData["DataFields"]["night_phone_a"] = _ml_substr($phone, -3);
                 }
             }
         }
     }
     if ($this->Settings['MODULE_ADDRESS_OVERRIDE'] == 1) {
         $shippingInfo = new ArrayAccessLayer($orderInfo);
         $shippingInfo->setAccessMask("Shipping", "attr", AAL_CUSTOM_PARAM, "value");
         $confirmationData["DataFields"]["address_override"] = "1";
         $confirmationData["DataFields"]["first_name"] = $shippingInfo->getByMask('Firstname');
         $confirmationData["DataFields"]["last_name"] = $shippingInfo->getByMask('Lastname');
         $confirmationData["DataFields"]["address1"] = $shippingInfo->getByMask('Streetline1');
         $confirmationData["DataFields"]["address2"] = $shippingInfo->getByMask('Streetline2');
         $confirmationData["DataFields"]["city"] = $shippingInfo->getByMask('City');
         $confirmationData["DataFields"]["state"] = modApiFunc("Location", "getStateCodeByStateName", $shippingInfo->getByMask('State'));
         if (!$confirmationData["DataFields"]["state"]) {
             $confirmationData["DataFields"]["state"] = $shippingInfo->getByMask('State');
         }
         $confirmationData["DataFields"]["zip"] = $shippingInfo->getByMask('Postcode');
         $confirmationData["DataFields"]["country"] = modApiFunc("Location", "getCountryCodeByCountryName", $shippingInfo->getByMask('Country'));
         $confirmationData["DataFields"]["email"] = $shippingInfo->getByMask('Email');
         if ($shippingInfo->getByMask('Phone')) {
             $phone = $shippingInfo->getByMask('Phone');
             $phone = preg_replace("/[^0-9]/", "", $phone);
             if (isset($confirmationData["DataFields"]["country"]) && $confirmationData["DataFields"]["country"] == "US") {
                 if (_ml_strlen($phone) == 10) {
                     $confirmationData["DataFields"]["night_phone_c"] = _ml_substr($phone, -4);
                     $phone = _ml_substr($phone, 0, -4);
                     $confirmationData["DataFields"]["night_phone_b"] = _ml_substr($phone, -3);
                     $phone = _ml_substr($phone, 0, -3);
                     $confirmationData["DataFields"]["night_phone_a"] = _ml_substr($phone, -3);
                 }
             }
         }
     }
     $confirmationData['FormAction'] = $this->Settings['MODULE_MODE'] == 1 ? PAYPAL_URL_TEST : PAYPAL_URL;
     //=========================== logging request ========================
     $msgObj = $application->getInstance("MessageResources", "payment-module-paypal-messages", "AdminZone");
     $title = $msgObj->getMessage("MODULE_PAYMENT_TIMELINE_HEADER_CONFIRMATION_DATA");
     $title = str_replace('{ORDER_ID}', $orderId, $title);
     $this->addRequestLog("LOG_PM_INPUT", "Payment Module Logs", $title, prepareArrayDisplay($confirmationData));
     //=========================== logging request ========================
     return $confirmationData;
 }
 function doWork($order_info)
 {
     $result = array();
     $result['Order Id'] = $order_info['ID'];
     $result['Order Date'] = $order_info['Date'];
     $result['Order Status'] = $order_info['Status'];
     $result['Order Payment Status'] = $order_info['PaymentStatus'];
     $result['Order Payment Method'] = $order_info['PaymentMethod'];
     $result['Order Payment Method Detail'] = $order_info['PaymentMethodDetail'];
     $result['Order Payment Processor Order Id'] = $order_info['PaymentProcessorOrderId'];
     $result['Order Shipping Method'] = $order_info['ShippingMethod'];
     $result['Order Track Id'] = $order_info['TrackId'];
     $result['Order Affiliate Id'] = $order_info['AffiliateId'];
     $result['Order Currency Code'] = $order_info['OrderCurrencyCode'];
     $result['Order Subtotal'] = $order_info['Price']['OrderSubtotal'];
     $result['Order Global Discount'] = $order_info['Price']['SubtotalGlobalDiscount'];
     $result['Order Promo Code Discount'] = $order_info['Price']['SubtotalPromoCodeDiscount'];
     $result['Order Quantity Discount'] = $order_info['Price']['QuantityDiscount'];
     $result['Order Discounted Subtotal'] = $order_info['Price']['DiscountedSubtotal'];
     $result['Order Total Shipping And Handling Cost'] = $order_info['Price']['TotalShippingAndHandlingCost'];
     $result['Order Tax Total'] = $order_info['Price']['OrderTaxTotal'];
     $result['Order Total'] = $order_info['Price']['OrderTotal'];
     $billing = new ArrayAccessLayer($order_info);
     $billing->setAccessMask("Billing", "attr", AAL_CUSTOM_PARAM, "value");
     $result['Order Billing Firstname'] = $billing->getByMask('Firstname');
     $result['Order Billing Lastname'] = $billing->getByMask('Lastname');
     $result['Order Billing Email'] = $billing->getByMask('Email');
     $result['Order Billing Streetline1'] = $billing->getByMask('Streetline1');
     $result['Order Billing Streetline2'] = $billing->getByMask('Streetline2');
     $result['Order Billing City'] = $billing->getByMask('City');
     $result['Order Billing State'] = $billing->getByMask('State');
     $result['Order Billing Postcode'] = $billing->getByMask('Postcode');
     $result['Order Billing Country'] = $billing->getByMask('Country');
     $result['Order Billing Phone'] = $billing->getByMask('Phone');
     $result['Order Billing CommentLine'] = $billing->getByMask('CommentLine');
     $result['Order Billing CommentArea'] = $billing->getByMask('CommentArea');
     $shipping = new ArrayAccessLayer($order_info);
     $shipping->setAccessMask("Shipping", "attr", AAL_CUSTOM_PARAM, "value");
     $result['Order Shipping Firstname'] = $shipping->getByMask('Firstname');
     $result['Order Shipping Lastname'] = $shipping->getByMask('Lastname');
     $result['Order Shipping Email'] = $shipping->getByMask('Email');
     $result['Order Shipping Streetline1'] = $shipping->getByMask('Streetline1');
     $result['Order Shipping Streetline2'] = $shipping->getByMask('Streetline2');
     $result['Order Shipping City'] = $shipping->getByMask('City');
     $result['Order Shipping State'] = $shipping->getByMask('State');
     $result['Order Shipping Postcode'] = $shipping->getByMask('Postcode');
     $result['Order Shipping Country'] = $shipping->getByMask('Country');
     $result['Order Shipping Phone'] = $shipping->getByMask('Phone');
     $result['Order Shipping CommentLine'] = $shipping->getByMask('CommentLine');
     $result['Order Shipping CommentArea'] = $shipping->getByMask('CommentArea');
     for ($i = 0; $i < count($order_info['Products']); $i++) {
         $j = $i + 1;
         $result['Order Product ' . $j . ' Name'] = $order_info['Products'][$i]['name'];
         $result['Order Product ' . $j . ' Quantity'] = $order_info['Products'][$i]['qty'];
         $result['Order Product ' . $j . ' Sale Price'] = $order_info['Products'][$i]['SalePrice'];
         $result['Order Product ' . $j . ' SKU'] = isset($order_info['Products'][$i]['SKU']) ? $order_info['Products'][$i]['SKU'] : '';
         $result['Order Product ' . $j . ' Weight'] = $order_info['Products'][$i]['Weight'];
         $result['Order Product ' . $j . ' Amount'] = $order_info['Products'][$i]['qty'] * $order_info['Products'][$i]['SalePrice'];
         if (!empty($order_info['Products'][$i]['options'])) {
             for ($oi = 0; $oi < count($order_info['Products'][$i]['options']); $oi++) {
                 $oj = $oi + 1;
                 $result['Order Product ' . $j . ' Option ' . $oj . ' Name'] = $order_info['Products'][$i]['options'][$oi]['option_name'];
                 $result['Order Product ' . $j . ' Option ' . $oj . ' Value'] = $order_info['Products'][$i]['options'][$oi]['option_value'];
             }
         }
     }
     for ($on = 0; $on < sizeof($order_info['Comments']); $on++) {
         $result['Date of Note ' . ($on + 1)] = $order_info['Comments'][$on]['date'];
         $result['Admin Note ' . ($on + 1)] = $order_info['Comments'][$on]['content'];
     }
     $this->_messages = "Order {$order_info['ID']} exported.";
     return $result;
 }
 function OnOrderCreated($order_id)
 {
     global $application;
     $account = $this->getCurrentSignedCustomer();
     $setting_first_order_only = modApiFunc("Settings", "getParamValue", "AFFILIATE_SETTINGS", "FIRST_ORDER_ONLY");
     $setting_update_affiliate = modApiFunc("Settings", "getParamValue", "AFFILIATE_SETTINGS", "UPDATE_AFFILIATE_ID");
     if (modApiFunc("Session", "is_set", "AffiliateID")) {
         if ($setting_first_order_only == "YES") {
             modApiFunc("Session", "un_set", "AffiliateID");
             $aff_id = "";
         } else {
             $aff_id = modApiFunc("Session", "get", "AffiliateID");
         }
     } else {
         $aff_id = "";
     }
     if ($account != null) {
         $obj =& $application->getInstance('CCustomerInfo', $account);
         # update affiliate id
         if ($setting_update_affiliate == "CURRENT" && !empty($obj->affiliate_id) && $setting_first_order_only != "YES") {
         } else {
             $obj->setAffiliateID($aff_id);
         }
     } else {
         $groups = array('billingInfo', 'shippingInfo');
         $email = null;
         reset($groups);
         loadCoreFile('aal.class.php');
         foreach ($groups as $group_name) {
             $Info = new ArrayAccessLayer(modApiFunc("Checkout", "getPrerequisiteValidationResults", $group_name));
             $Info->setAccessMask("validatedData", AAL_CUSTOM_PARAM, "value");
             $em = $Info->getByMask("Email");
             if ($em != '') {
                 $email = $em;
                 break;
             }
         }
         $settings = $this->getSettings();
         if ($settings['CHECKOUT_TYPE'] == CHECKOUT_TYPE_QUICK or $settings['CHECKOUT_TYPE'] == CHECKOUT_TYPE_AUTOACCOUNT and $settings['AUTO_CREATE_ACCOUNT'] == 'N') {
             if ($settings['CHECKOUT_TYPE'] == CHECKOUT_TYPE_AUTOACCOUNT && $settings['AUTO_CREATE_ACCOUNT'] == 'N' && $settings['MERGE_ORDERS_BY_EMAIL'] == 'Y' && $email != null) {
                 $account_name = $email;
                 if ($this->doesAccountExists($account_name) == false || $this->getAccountStatus($account_name) != "A") {
                     $account_name = ($email != null ? $email : PSEUDO_NA_CUSTOMER_PERFIX . $order_id) . PSEUDO_CUSTOMER_SUFFIX;
                 }
             } else {
                 $account_name = ($email != null ? $email : PSEUDO_NA_CUSTOMER_PERFIX . $order_id) . PSEUDO_CUSTOMER_SUFFIX;
                 if ($this->doesAccountExists($account_name) && $settings['MERGE_ORDERS_BY_EMAIL'] == 'N') {
                     $account_name = $this->__genAutoAccountName();
                 }
             }
             if ($this->doesAccountExists($account_name)) {
                 $obj =& $application->getInstance('CCustomerInfo', $account_name);
             } else {
                 $this->addAccount($account_name, time(), $aff_id);
                 $this->setAccountStatus($account_name, 'B');
                 $obj =& $application->getInstance('CCustomerInfo', $account_name);
                 $obj->loadPersonInfoFromCheckout();
                 if ($email != null) {
                     $obj->setPersonInfo(array(array('Email', $email, 'Customer')));
                 }
                 if ($this->isPersionInfoGroupActive('Billing')) {
                     $obj->copyPersonInfo('Billing', 'Customer', array('Email'));
                 } elseif ($this->isPersionInfoGroupActive('Shipping')) {
                     $obj->copyPersonInfo('Shipping', 'Customer', array('Email'));
                 }
             }
         } else {
             #
             # here we should check if we can use email as login
             #
             $throwAutoAccCreated = false;
             if ($email != null) {
                 $account_name = $email;
                 if ($this->doesAccountExists($account_name)) {
                     # check settings if order should be merged or new account created.
                     if ($settings['MERGE_ORDERS_BY_EMAIL'] == 'Y') {
                         # do nothing?
                     } else {
                         $account_name = $this->__genAutoAccountName();
                         $this->addAccount($account_name, time(), $aff_id);
                         $this->setAccountStatus($account_name, 'R');
                         $this->replaceActivationKey($account_name);
                         $throwAutoAccCreated = true;
                     }
                 } else {
                     $this->addAccount($account_name, time(), $aff_id);
                     $this->setAccountStatus($account_name, 'R');
                     $this->replaceActivationKey($account_name);
                     $throwAutoAccCreated = true;
                 }
             } else {
                 $account_name = $this->__genAutoAccountName();
                 # here the account name is unique and not duplicated for sure
                 # if no email provided then each user/order will be treated as unique
                 $this->addAccount($account_name, time(), $aff_id);
                 $this->setAccountStatus($account_name, 'R');
                 $this->replaceActivationKey($account_name);
                 $throwAutoAccCreated = true;
             }
             $obj =& $application->getInstance('CCustomerInfo', $account_name);
             if ($throwAutoAccCreated == true) {
                 $obj->setPersonInfo(array(array('AccountName', $account_name, 'Customer')));
                 $obj->loadPersonInfoFromCheckout();
                 if ($email != null) {
                     $obj->setPersonInfo(array(array('Email', $email, 'Customer')));
                 } else {
                     if ($email == null && preg_match("/" . ANONYMOUS_ACCOUNT_NAME . "/", $account_name)) {
                         $obj->setPersonInfo(array(array('Email', $account_name, 'Customer')));
                     }
                 }
                 if ($this->isPersionInfoGroupActive('Billing')) {
                     $obj->copyPersonInfo('Billing', 'Customer', array('Email'));
                 } elseif ($this->isPersionInfoGroupActive('Shipping')) {
                     $obj->copyPersonInfo('Shipping', 'Customer', array('Email'));
                 }
                 modApiFunc('EventsManager', 'throwEvent', 'AccountWasAutoCreated', $account_name);
             }
         }
     }
     modApiFunc('Customer_Account', 'setAccountLanguage', $obj->getPersonInfo('Account'), modApiFunc('MultiLang', 'getLanguage'));
     modApiFunc('Customer_Account', 'setAccountNotificationLanguage', $obj->getPersonInfo('Account'), modApiFunc('MultiLang', 'getLanguage'));
     $obj->__loadBaseInfo();
     $ca_tables = modApiStaticFunc('Checkout', 'getTables');
     $orders_table = $ca_tables['orders']['columns'];
     $query = new DB_Update('orders');
     $query->addUpdateValue($orders_table['person_id'], $obj->getPersonInfo('ID'));
     $query->WhereValue($orders_table['id'], DB_EQ, $order_id);
     $application->db->PrepareSQL($query);
     $application->db->DB_Exec();
     return;
 }
Пример #4
0
 /**
  *               $symbolic = true,                                   ,                {p_1} -
  *               .                                   _   _       ,
  *     _ _        .      ,      $symbolic = false,                                      -      ,
  *       ,                _   _       .
  * @param
  * @return
  */
 function calculateTax(&$thisTaxAmounts, &$Taxes, $TaxId, $TaxRatesList, $AddressesList, $ProductsList, $CartSubtotal, $OrderLevelShippingCost, $TotalShippingCost, $ShippingMethod, $OrderLevelDiscount, $TotalDiscount, $currency_id, $debug, $trace, $symbolic, $md5 = NULL)
 {
     global $application;
     $MessageResources =& $application->getInstance('MessageResources');
     $retval = "";
     if ($Taxes[$TaxId]["applicable"]) {
         if ($Taxes[$TaxId]["status"] == "in_progress") {
             $Taxes[$TaxId]["status"] = "na";
             //                if ($trace)
             //                {
             //                    $TaxInfo = $this->getTaxNameInfo($TaxId);
             //                    $TraceInfo = array(
             //                                       "TaxId" => $TaxId,
             //                                       "Message"      => $MessageResources->getMessage( new ActionMessage(array('TAX_CALCULATOR_WRN_009', $TaxInfo["Name"])))
             //                                      );
             //                    $this->addTraceInfo("6", $TraceInfo);
             //                }
             return "fatal";
         }
         if ($Taxes[$TaxId]["status"] == "calculated") {
             return;
         }
         $Taxes[$TaxId]["status"] = "in_progress";
         $_TaxRatesList = $this->excludeTaxRates($TaxRatesList, array("entity" => "Tax", "TaxNameId" => $TaxId));
         //            if ($trace)
         //            {
         //                $TaxInfo = $this->getTaxNameInfo($TaxId);
         //                $TraceInfo = array(
         //                                   "TaxId" => $TaxId
         //                                  ,"TaxName"      => $TaxInfo["Name"]
         //                                  ,"Address"      => $MessageResources->getMessage(sprintf("TAX_ADDRESS_NAME_%03d", $TaxInfo["AddressId"]))
         //                                  ,"TaxRatesList" => $_TaxRatesList
         //                                  );
         //                $this->addTraceInfo("3", $TraceInfo);
         //            }
         //                   ,          "                 ",
         //       .                                        .                          (
         //             Store Owner Address)                            (
         //  country_id, state_id),    "                ""
         //                         .                                      "
         //                    ",                                                 .
         //                                      .         ,            Checkout CZ.
         //                                                 .                       ,
         //            .
         //                        ,     "                "
         //                                 .                     .         ,                      .
         if ($Taxes[$TaxId]["needs_address"] == DB_TRUE && $AddressesList[$Taxes[$TaxId]["address"]] === NULL) {
             //                        default address       -                .
             if ($Taxes[$TaxId]["included_into_price"] === "true" && $AddressesList[0] !== NULL) {
                 $__TaxRatesList = $this->excludeTaxRates($_TaxRatesList, array("entity" => "Address", "CountryId" => $AddressesList[0]["CountryId"], "StateId" => $AddressesList[0]["StateId"]));
             } else {
                 //"                "           .                                                  ,
                 //              "                                                            "
                 //           .
                 //                                .
                 $__TaxRatesList = $this->excludeTaxRates($_TaxRatesList, array("entity" => "Address", "CountryId" => NULL, "StateId" => NULL));
             }
         } else {
             if ($Taxes[$TaxId]["needs_address"] == DB_TRUE) {
                 //                            .
                 //                                        ,     "                  "
                 //                                    .
                 //                        default address       -                .
                 if ($Taxes[$TaxId]["included_into_price"] === "true") {
                     if ($AddressesList[0] !== NULL) {
                         $__TaxRatesList = $this->excludeTaxRates($_TaxRatesList, array("entity" => "Address", "CountryId" => $AddressesList[0]["CountryId"], "StateId" => $AddressesList[0]["StateId"]));
                     } else {
                         //                         .
                         //                       "                ."
                         //                             PRICE_N_A.
                         $__TaxRatesList = $this->excludeTaxRates($_TaxRatesList, array("entity" => "Address", "CountryId" => NULL, "StateId" => NULL));
                     }
                 } else {
                     //      "            ".                                           .
                     $__TaxRatesList = $this->excludeTaxRates($_TaxRatesList, array("entity" => "Address", "CountryId" => $AddressesList[$Taxes[$TaxId]["address"]]["CountryId"], "StateId" => $AddressesList[$Taxes[$TaxId]["address"]]["StateId"]));
                 }
             } else {
                 $__TaxRatesList = $_TaxRatesList;
                 //                                                .                                   .
             }
         }
         //            if ($trace)
         //            {
         //                global $application;
         //                $MessageResources = &$application->getInstance('MessageResources');
         //                $TraceInfo = array(
         //                                   "TaxId" => $TaxId
         //                                  ,"Address"      => $MessageResources->getMessage(sprintf('TAX_ADDRESS_NAME_%03d', $Taxes[$TaxId]["address"]))
         //                                  ,"CountryId" => $this->TaxDebug["AddressesList"][$Taxes[$TaxId]["address"]]["CountryId"]
         //                                  ,"StateId" => $this->TaxDebug["AddressesList"][$Taxes[$TaxId]["address"]]["StateId"]
         //                                  ,"TaxRatesList" => $__TaxRatesList
         //                                  );
         //                $this->addTraceInfo("4", $TraceInfo);
         //            }
         foreach ($ProductsList as $ProductInfo) {
             $thisTaxAmounts["products"][$ProductInfo["CartID"]][$TaxId] = (int) PRICE_N_A;
             //0;
             /*
             if ($ProductInfo["attributes"]["TaxClass"]["value"] == TAX_CLASS_ID_NOT_TAXABLE)
             {
                 continue;
             }
             */
             $___TaxRatesList = $this->excludeTaxRates($__TaxRatesList, array("entity" => "TaxClass", "ProductTaxClassId" => $ProductInfo["attributes"]["TaxClass"]["value"]));
             //                if ($trace)
             //                {
             //                    $ProdTaxClass = $this->getProductTaxClassInfo($ProductInfo["attributes"]["TaxClass"]["value"]);
             //                    $TraceInfo = array(
             //                                       "TaxId" => $TaxId
             //                                      ,"ProdInfo" => $ProductInfo
             //                                      ,"ProductTaxClass"      => $ProdTaxClass['value']
             //                                      ,"TaxRatesList" => $___TaxRatesList
             //                                      );
             //                    $this->addTraceInfo("5", $TraceInfo);
             //                }
             if (sizeof($___TaxRatesList) == 0) {
                 $this->TaxAmounts["products"][$ProductInfo["ID"]][$TaxId] = 0;
                 $Taxes[$TaxId]["status"] = "na";
                 //                    if ($trace)
                 //                    {
                 //                        $TaxInfo = $this->getTaxNameInfo($TaxId);
                 //                        $TraceInfo = array(
                 //                                           "TaxId" => $TaxId,
                 //                                           "Message"      => $MessageResources->getMessage( new ActionMessage(array('TAX_CALCULATOR_WRN_013', prepareHTMLDisplay($TaxInfo["Name"]), "Product ".$ProductInfo["CartID"])))
                 //                                          );
                 //                        $this->addTraceInfo("6", $TraceInfo);
                 //                    }
                 continue;
             }
             //                  ALL_STATES                NEW_YORK,              .
             //    NEW_YORK -         .
             if ($Taxes[$TaxId]["needs_address"] == DB_TRUE && isset($AddressesList[$Taxes[$TaxId]["address"]]) && isset($AddressesList[$Taxes[$TaxId]["address"]]["StateId"]) && $AddressesList[$Taxes[$TaxId]["address"]]["StateId"] != NULL && $AddressesList[$Taxes[$TaxId]["address"]]["StateId"] != 0 && is_numeric($AddressesList[$Taxes[$TaxId]["address"]]["StateId"])) {
                 $___TaxRatesList = $this->excludeTaxRates($___TaxRatesList, array("entity" => "State", "StateId" => $AddressesList[$Taxes[$TaxId]["address"]]["StateId"]));
             }
             if (sizeof($___TaxRatesList) > 1) {
                 $this->TaxAmounts["products"][$ProductInfo["ID"]][$TaxId] = 0;
                 $Taxes[$TaxId]["status"] = "na";
                 //                    if ($trace)
                 //                    {
                 //                        $TaxInfo = $this->getTaxNameInfo($TaxId);
                 //                        $TraceInfo = array(
                 //                                           "TaxId" => $TaxId,
                 //                                           "Message"      => $MessageResources->getMessage( new ActionMessage(array('TAX_CALCULATOR_WRN_010', prepareHTMLDisplay($TaxInfo["Name"]))))
                 //                                          );
                 //                        $this->addTraceInfo("6", $TraceInfo);
                 //                    }
                 continue;
             }
             if ($___TaxRatesList[0]["Applicable"] == "false") {
                 continue;
             }
             //                                                        .
             $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('{p_1}' => '<p_1>'));
             if (!($selected_sm = $this->getTaxSetting('SELECTED_SHIPPING_MODULES_LIST'))) {
                 $selected_sm = "a:0:{}";
             }
             $selected_sm = unserialize($selected_sm);
             if (!in_array($ShippingMethod, $selected_sm)) {
                 if ($TotalShippingCost == PRICE_N_A) {
                     $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('{p_2}' => PRICE_N_A));
                 } elseif ($TotalShippingCost == 0) {
                     $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('{p_2}' => 0));
                 } else {
                     //                                 ,    PerOrderShippingCost
                     //                              .
                     //                                    0,  . .                                0,
                     //               PerOrdershippingCost                                            .
                     $cart_quantity = modApiFunc("Cart", "getCartProductsQuantity");
                     if ($CartSubtotal == 0.0) {
                         if ($cart_quantity == 0) {
                             $order_level_shipping_cost_share = $OrderLevelShippingCost;
                         } else {
                             $order_level_shipping_cost_share = $OrderLevelShippingCost * ($ProductInfo["Quantity_In_Cart"] / $cart_quantity);
                         }
                     } else {
                         $price = isset($ProductInfo["CartItemSalePriceExcludingTaxes"]) ? $ProductInfo["CartItemSalePriceExcludingTaxes"] : $ProductInfo["CartItemSalePrice"];
                         $order_level_shipping_cost_share = $OrderLevelShippingCost * $price / $CartSubtotal;
                     }
                     $shippingCostModifier = isset($ProductInfo["OptionsModifiers"]["shipping_cost"]) ? $ProductInfo["OptionsModifiers"]["shipping_cost"] : 0;
                     $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('{p_2}' => ($ProductInfo["attributes"]["PerItemShippingCost"]["value"] ? $ProductInfo["attributes"]["PerItemShippingCost"]["value"] : 0) + ($ProductInfo["attributes"]["PerItemHandlingCost"]["value"] ? $ProductInfo["attributes"]["PerItemHandlingCost"]["value"] : 0) + $order_level_shipping_cost_share + $shippingCostModifier));
                 }
             } else {
                 $thisTaxAmounts["tax_on_shipping"] = false;
                 $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('{p_2}' => 0));
             }
             //                    Discount:
             if (_ml_strpos($___TaxRatesList[0]["Formula"], '{p_3}') !== FALSE) {
                 if ($TotalDiscount === COMPUTATION_POSTPONED) {
                     $TotalDiscount = modApiFunc("Checkout", "getOrderPrice", "DiscountsSum", $currency_id);
                 }
                 if ($OrderLevelDiscount === COMPUTATION_POSTPONED) {
                     $OrderLevelDiscount = $TotalDiscount - modApiFunc("Checkout", "getOrderPrice", "QuantityDiscount", $currency_id);
                 }
                 if ($TotalDiscount == PRICE_N_A || $TotalDiscount == 0) {
                     $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('{p_3}' => 0));
                 } else {
                     //                                 ,    PerOrderDiscount
                     //                              .
                     //                                    0,  . .                                0,
                     //               PerOrderDiscount                                            .
                     $cart_quantity = modApiFunc("Cart", "getCartProductsQuantity");
                     if ($CartSubtotal == 0.0) {
                         if ($cart_quantity == 0) {
                             $order_level_discount_share = $OrderLevelDiscount;
                         } else {
                             $order_level_discount_share = $OrderLevelDiscount * ($ProductInfo["Quantity_In_Cart"] / $cart_quantity);
                         }
                     } else {
                         #12.01 $order_level_discount_share = $OrderLevelDiscount*$ProductInfo["CartItemSalePrice"] / $CartSubtotal;
                         $price = isset($ProductInfo["CartItemSalePriceExcludingTaxes"]) ? $ProductInfo["CartItemSalePriceExcludingTaxes"] : $ProductInfo["CartItemSalePrice"];
                         $order_level_discount_share = $OrderLevelDiscount * $price / $CartSubtotal;
                     }
                     $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('{p_3}' => ($ProductInfo["PerItemDiscount"] ? $ProductInfo["PerItemDiscount"] : 0) + $order_level_discount_share));
                 }
             }
             if (!isset($thisTaxAmounts["products"][$ProductInfo["CartID"]]["tax_rate_id"])) {
                 $thisTaxAmounts["products"][$ProductInfo["CartID"]]["tax_rate_id"] = array();
             }
             //                if ($trace)
             //                {
             //                    $AdditionalMessage = "";
             //                }
             while (!(_ml_strpos($___TaxRatesList[0]["Formula"], '{t_') === false)) {
                 $pos = _ml_strpos($___TaxRatesList[0]["Formula"], '{t_');
                 $_taxId = _ml_substr($___TaxRatesList[0]["Formula"], $pos + 3, _ml_strpos($___TaxRatesList[0]["Formula"], '}') - ($pos + 3));
                 if (!isset($thisTaxAmounts["products"][$ProductInfo["CartID"]][$_taxId])) {
                     $thisTaxAmounts["products"][$ProductInfo["CartID"]][$_taxId] = 0;
                 }
                 if (!isset($thisTaxAmounts["products"][$ProductInfo["CartID"]]["tax_rate_id"][$_taxId])) {
                     $thisTaxAmounts["products"][$ProductInfo["CartID"]]["tax_rate_id"][$_taxId] = 0;
                 }
                 $retval = $this->calculateTax($thisTaxAmounts, $Taxes, $_taxId, $TaxRatesList, $AddressesList, $ProductsList, $CartSubtotal, $OrderLevelShippingCost, $TotalShippingCost, $ShippingMethod, $OrderLevelDiscount, $TotalDiscount, $currency_id, $debug, $trace, $symbolic);
                 if ($retval == "fatal") {
                     return $retval;
                 }
                 if ($thisTaxAmounts["products"][$ProductInfo["CartID"]][$_taxId] == PRICE_N_A) {
                     $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array("{t_" . $_taxId . "}" => PRICE_N_A));
                 } else {
                     if (is_array($thisTaxAmounts["products"][$ProductInfo["CartID"]][$_taxId])) {
                         $factors = $thisTaxAmounts["products"][$ProductInfo["CartID"]][$_taxId];
                         //                        .                                                 .
                         $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array("{t_" . $_taxId . "}" => $factors['k'] . " * <p_1> + " . $factors['b']));
                     } else {
                         $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array("{t_" . $_taxId . "}" => $thisTaxAmounts["products"][$ProductInfo["CartID"]][$_taxId]));
                     }
                 }
                 //                    if ($trace)
                 //                    {
                 //                        $TaxInfo = $this->getTaxNameInfo($_taxId);
                 //                        $AdditionalMessage.= $MessageResources->getMessage(new ActionMessage(array('TAX_CALCULATOR_WRN_012', prepareHTMLDisplay($TaxInfo["Name"]), modApiFunc("Localization", "format", $thisTaxAmounts["products"][$ProductInfo["CartID"]][$_taxId], "currency"), "Product ".$ProductInfo["CartID"])))."<br>";
                 //                    }
             }
             if (_ml_strpos($___TaxRatesList[0]["Formula"], sprintf("%d", PRICE_N_A)) === false) {
                 if ($symbolic === true) {
                     //                                                  {p_1}.                               -
                     //                           ,                                _   _       ,        _ _        .
                     $factors = array("k" => NULL, "b" => NULL);
                     $b_is_linear = $this->isTaxFormulaLinear($___TaxRatesList[0]["Formula"], $___TaxRatesList[0]["Rate"], "<p_1>", $factors);
                     if ($b_is_linear === false) {
                         $thisTaxAmounts["products"][$ProductInfo["CartID"]][$TaxId] = TAX_NOT_LINEAR;
                         //: report error.   CZ                                   .
                     } else {
                         $thisTaxAmounts["products"][$ProductInfo["CartID"]][$TaxId] = $factors;
                         //SYMBOLIC_TAX_VALUE;
                     }
                 } else {
                     loadCoreFile('aal.class.php');
                     //print prepareArrayDisplay($___TaxRatesList);
                     //print prepareArrayDisplay(debug_backtrace());
                     $sid = $___TaxRatesList[0]["rates_set"];
                     if ($sid != 0) {
                         if ($Taxes[$TaxId]["address"] == 1) {
                             $shippingInfo = new ArrayAccessLayer(modApiFunc("Checkout", "getPrerequisiteValidationResults", "shippingInfo"));
                             $shippingInfo->setAccessMask("validatedData", AAL_CUSTOM_PARAM, "value");
                             $zip = $shippingInfo->getByMask('Postcode');
                             $rate = modApiFunc("TaxRateByZip", "getTaxRateByZip", $sid, $zip);
                         } else {
                             if ($Taxes[$TaxId]["address"] == 2) {
                                 $billingInfo = new ArrayAccessLayer(modApiFunc("Checkout", "getPrerequisiteValidationResults", "billingInfo"));
                                 $billingInfo->setAccessMask("validatedData", AAL_CUSTOM_PARAM, "value");
                                 $zip = $billingInfo->getByMask('Postcode');
                                 $rate = modApiFunc("TaxRateByZip", "getTaxRateByZip", $sid, $zip);
                             }
                         }
                     } else {
                         $rate = $___TaxRatesList[0]["Rate"];
                     }
                     $___TaxRatesList[0]["Formula"] = strtr($___TaxRatesList[0]["Formula"], array('<p_1>' => $ProductInfo["CartItemSalePriceExcludingTaxes"]));
                     $thisTaxAmounts["products"][$ProductInfo["CartID"]][$TaxId] = $rate * eval("return " . $___TaxRatesList[0]["Formula"] . ";") / 100.0;
                 }
             } else {
                 $thisTaxAmounts["products"][$ProductInfo["CartID"]][$TaxId] = (int) PRICE_N_A;
             }
             $thisTaxAmounts["products"][$ProductInfo["CartID"]]["tax_rate_id"][$TaxId] = $___TaxRatesList[0]["Id"];
             //                if ($trace)
             //                {
             //                    $TaxInfo = $this->getTaxNameInfo($TaxId);
             //                    $TraceInfo = array(
             //                                       "TaxId" => $TaxId,
             //                                       "Message" => $AdditionalMessage.$MessageResources->getMessage(new ActionMessage(array('TAX_CALCULATOR_WRN_011', prepareHTMLDisplay($TaxInfo["Name"]), modApiFunc("Localization", "format", $thisTaxAmounts["products"][$ProductInfo["CartID"]][$TaxId], "currency"), $ProductInfo["Quantity_In_Cart"], modApiFunc("Localization", "format", ($thisTaxAmounts["products"][$ProductInfo["CartID"]][$TaxId]*$ProductInfo["Quantity_In_Cart"]), "currency"), "Product ".$ProductInfo["CartID"])))
             //                                      );
             //                    $this->addTraceInfo("6", $TraceInfo);
             //                }
         }
         //            if ($trace)
         //            {
         //                $TraceInfo = array("TaxId" => $TaxId);
         //                $this->addTraceInfo("7", $TraceInfo);
         //            }
         $Taxes[$TaxId]["status"] = "calculated";
     }
     return $retval;
 }