Guest User

Untitled

a guest
Jun 13th, 2017
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 40.92 KB | None | 0 0
  1. <? if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true)
  2.     die();
  3.  
  4. use Bitrix\Main;
  5. use Bitrix\Sale;
  6. use Bitrix\Main\Config;
  7. use Bitrix\Main\Data;
  8. use Bitrix\Main\Loader;
  9. use Bitrix\Main\Localization\Loc;
  10. use Bitrix\Sale\Delivery;
  11. use Bitrix\Catalog\Product\Sku;
  12.  
  13. Loc::loadMessages(__FILE__);
  14.  
  15. class BuyOneClick extends CBitrixComponent{
  16.    
  17.     private $element_id;
  18.     protected $requestData = array();
  19.     protected $ajax_id;
  20.     protected $userAuth;
  21.     protected $userID;
  22.     protected $show_captha;
  23.     protected $arOffers;
  24.     protected $currentCache = null;
  25.     protected $templateName = "";
  26.     protected $needGetData = false;
  27.     /**
  28.      * Fatal error list. Any fatal error makes useless further execution of a component code.
  29.      * In most cases, there will be only one error in a list according to the scheme "one shot - one dead body"
  30.      *
  31.      * @var string[] Array of fatal errors.
  32.      */
  33.     protected $errorsFatal = array();
  34.    
  35.     /**
  36.      * Non-fatal error list. Some non-fatal errors may occur during component execution, so certain functions of the component
  37.      * may became defunct. Still, user should stay informed.
  38.      * There may be several non-fatal errors in a list.
  39.      *
  40.      * @var string[] Array of non-fatal errors.
  41.      */
  42.     protected $errorsNonFatal = array();
  43.    
  44.    
  45.    
  46.     public function onPrepareComponentParams($arParams){
  47.         global $USER;
  48.         // common
  49.         $arParams['SHOW_DELIVERY'] = ($arParams['SHOW_DELIVERY'] == 'Y' ? true : false);
  50.         $arParams['SHOW_PAY_SYSTEM'] = ($arParams['SHOW_PAY_SYSTEM'] == 'Y' ? true : false);
  51.         $arParams['SHOW_USER_DESCRIPTION'] = ($arParams['SHOW_USER_DESCRIPTION'] == 'Y' ? true : false);
  52.         $arParams['CREATE_NEW_USER'] = ($arParams['CREATE_NEW_USER'] == 'Y' ? true : false);
  53.         $arParams['SEND_MAIL'] = ($arParams['SEND_MAIL'] == 'Y' ? true : false);
  54.         $arParams['SEND_MAIL_REQ'] = ($arParams['SEND_MAIL_REQ'] == 'Y' ? true : false);
  55.         $arParams['SHOW_QUANTITY'] = ($arParams['SHOW_QUANTITY'] == 'Y' ? true : false);
  56.         $arParams['BUY_CURRENT_BASKET'] = ($arParams['BUY_CURRENT_BASKET'] == 'Y' ? true : false);
  57.         $arParams['PATH_TO_PAYMENT'] = strlen($arParams['PATH_TO_PAYMENT'])>0?$arParams['PATH_TO_PAYMENT']:"/personal/order/payment/";
  58.         $arParams['NOT_AUTHORIZE_USER'] = ($arParams['NOT_AUTHORIZE_USER'] == 'Y' ? true : false);
  59.         $arParams['ALLOW_ORDER_FOR_EXISTING_EMAIL'] = ($arParams['ALLOW_ORDER_FOR_EXISTING_EMAIL'] == 'Y' ? true : false);
  60.         $arParams['ADD_NOT_AUTH_TO_ONE_USER'] = ($arParams['ADD_NOT_AUTH_TO_ONE_USER'] == 'Y' ? true : false);
  61.         $arParams['ADD_NOT_AUTH_TO_ONE_USER_ID'] = intval($arParams['ADD_NOT_AUTH_TO_ONE_USER_ID']);
  62.        
  63.        
  64.         if(!class_exists("Bitrix\Sale\Delivery\Services\Manager") ||
  65.             !method_exists("Bitrix\Sale\Delivery\Services\Manager", "getActiveList") ||
  66.             !class_exists("Bitrix\Sale\Delivery\Services\Table")){
  67.             $arParams['USE_OLD_CLASS'] = 'Y';
  68.         }
  69.        
  70.         return $arParams;
  71.     }
  72.    
  73.    
  74.     /** new component function  */
  75.    
  76.     private function prepareData(){
  77.         global $APPLICATION;
  78.        
  79.         $this->arResult = array();
  80.         if($this->needGetData){
  81.             $this->arResult['PAY_SYSTEM'] = $this->getPaySystem();
  82.             $this->arResult['DELIVERY'] = $this->getDelivery();
  83.             $this->arResult['USER_FIELDS'] = $this->getUserFields();
  84.             $this->arResult['USER_FIELDS_REQUIRED'] = $this->getUserFieldsRequire();
  85.             $this->arResult['SHOW_PROPERTIES'] = $this->getOrderProps();
  86.             $this->arResult['SHOW_PROPERTIES_REQUIRED'] = $this->getOrderPropsRequire();
  87.             $this->arResult['CURRENT_USER_FIELDS'] = $this->getCurrentUser();
  88.             $this->arResult['CURRENT_USER_PROPS'] = $this->getCurrentUserProps();
  89.             $this->arResult['POST'] = $this->requestData;
  90.            
  91.            
  92.             if(!empty($this->requestData['H2O_B1C_OFFER_ID'])){ //H2O_B1C_ - для обхода конфликтов с другими компонентами
  93.                 $this->element_id = $this->requestData['H2O_B1C_OFFER_ID'];
  94.             }
  95.             elseif(intval($this->requestData['H2O_B1C_ELEMENT_ID']) > 0){  //H2O_B1C_ - для обхода конфликтов с другими компонентами
  96.                 $this->element_id = $this->requestData['H2O_B1C_ELEMENT_ID'];
  97.             }
  98.             elseif(!empty($this->requestData['OFFER_ID'])){    //для старых шаблонов
  99.                 $this->element_id = $this->requestData['OFFER_ID'];
  100.             }
  101.             elseif(intval($this->requestData['ELEMENT_ID']) > 0){  //для старых шаблонов
  102.                 $this->element_id = $this->requestData['ELEMENT_ID'];
  103.             }
  104.             else{
  105.                 $this->element_id = $this->arParams['ELEMENT_ID'];
  106.             }
  107.            
  108.             $this->arResult['ELEMENT_ID'] = $this->element_id;
  109.             if($this->arParams["SHOW_OFFERS_FIRST_STEP"] == 'Y'){
  110.                 if(intval($this->requestData['H2O_B1C_ELEMENT_ID']) > 0){
  111.                     $this->arResult['OFFERS'] = $this->getOffers(intval($this->requestData['H2O_B1C_ELEMENT_ID']));
  112.                     $this->arResult['ELEMENT_ID'] = intval($this->requestData['H2O_B1C_ELEMENT_ID']);
  113.                     $this->arResult['CURRENT_OFFER_ID'] = intval($this->requestData['H2O_B1C_OFFER_ID']);
  114.                 }
  115.                 elseif(intval($this->requestData['ELEMENT_ID']) > 0){
  116.                     $this->arResult['OFFERS'] = $this->getOffers(intval($this->requestData['ELEMENT_ID']));
  117.                     $this->arResult['ELEMENT_ID'] = intval($this->requestData['ELEMENT_ID']);
  118.                     $this->arResult['CURRENT_OFFER_ID'] = intval($this->requestData['OFFER_ID']);
  119.                 }
  120.                 else{
  121.                     $this->arResult['OFFERS'] = $this->getOffers(intval($this->arParams['ELEMENT_ID']));
  122.                     $this->arResult['ELEMENT_ID'] = intval($this->arParams['ELEMENT_ID']);
  123.                    
  124.                 }
  125.             }
  126.            
  127.             $this->arResult['QUANTITY'] = (floatval($this->requestData['quantity_b1c']) > 0) ?
  128.                 floatval($this->requestData['quantity_b1c']) :
  129.                 1;
  130.             $this->arResult['CURRENT_PRODUCT'] = $this->getCurrentProduct($this->arResult['ELEMENT_ID'], $this->arResult['QUANTITY']);
  131.            
  132.             if($this->show_captha){
  133.                 include_once($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/captcha.php");
  134.                 $this->arResult["capCode"] = htmlspecialcharsbx($APPLICATION->CaptchaGetCode());
  135.             }
  136.             $this->arResult["SHOW_CAPTCHA"] = $this->show_captha ? "Y" : "N";
  137.         }
  138.         $this->arResult["AJAX_ID"] = $this->ajax_id;
  139.        
  140.         //return $arFields;
  141.     }
  142.    
  143.     private function getPaySystem(){
  144.         if ($this->startCache(array('b1c-paysystem')))
  145.         {
  146.             try
  147.             {
  148.                
  149.                
  150.                 if($this->arParams['MODE_EXTENDED'] == 'Y'){
  151.                     if(!empty($this->arParams['PAY_SYSTEMS'])){
  152.                         $db_ptype = CSalePaySystem::GetList($arOrder = Array("SORT" => "ASC", "PSA_NAME" => "ASC"), Array("ACTIVE" => "Y", "PERSON_TYPE_ID" => $this->arParams['PERSON_TYPE_ID'], "ID" => $this->arParams['PAY_SYSTEMS']));
  153.                     }else{
  154.                         $db_ptype = CSalePaySystem::GetList($arOrder = Array("SORT" => "ASC", "PSA_NAME" => "ASC"), Array("ACTIVE" => "Y", "PERSON_TYPE_ID" => $this->arParams['PERSON_TYPE_ID']));
  155.                     }
  156.                 }else{
  157.                     $db_ptype = CSalePaySystem::GetList($arOrder = Array("SORT" => "ASC", "PSA_NAME" => "ASC"), Array("ACTIVE" => "Y", "PERSON_TYPE_ID" => $this->arParams['PERSON_TYPE_ID']));
  158.                 }
  159.                 $arPaySystems = array();
  160.                 while($arPaySystem = $db_ptype->Fetch()){
  161.                     if($arPaySystem["PSA_LOGOTIP"] > 0)
  162.                         $arPaySystem["PSA_LOGOTIP"] = CFile::GetFileArray($arPaySystem["PSA_LOGOTIP"]);
  163.                     $arPaySystem["PSA_NAME"] = htmlspecialcharsEx($arPaySystem["PSA_NAME"]);
  164.                     $arPaySystems[] = $arPaySystem;
  165.                 }
  166.                
  167.             }
  168.             catch (Exception $e)
  169.             {
  170.                 $this->abortCache();
  171.                 throw $e;
  172.             }
  173.            
  174.             $this->endCache($arPaySystems);
  175.            
  176.         }
  177.         else
  178.             $arPaySystems = $this->getCacheData();
  179.        
  180.        
  181.         return $arPaySystems;
  182.     }
  183.    
  184.     private function getDelivery(){
  185.         if ($this->startCache(array('b1c-delivery')))
  186.         {
  187.             try
  188.             {
  189.                 $arDelivery = array();
  190.                 if($this->arParams["USE_OLD_CLASS"] != 'Y'){
  191.                     $arDeliveryActive = Delivery\Services\Manager::getActiveList();
  192.                     if($this->arParams['MODE_EXTENDED'] == 'Y'){
  193.                         if(!empty($this->arParams['DELIVERY'])){
  194.                             $arDelivery = array_intersect_key($arDeliveryActive, array_flip($this->arParams['DELIVERY']));
  195.                         }else{
  196.                             $arDelivery = $arDeliveryActive;
  197.                         }
  198.                     }else{
  199.                         $deliveryId = Delivery\Services\EmptyDeliveryService::getEmptyDeliveryServiceId();
  200.                         $arDelivery[] = Delivery\Services\Manager::getById($deliveryId);
  201.                     }
  202.                 }else{
  203.                     if($this->arParams['MODE_EXTENDED'] == 'Y'){
  204.                         if(!empty($this->arParams['DELIVERY'])){
  205.                             $db_dtype = CSaleDelivery::GetList(array(
  206.                                 "SORT" => "ASC",
  207.                                 "NAME" => "ASC"
  208.                             ), array(
  209.                                 "ACTIVE" => "Y",
  210.                                 "ID" => $this->arParams['DELIVERY']
  211.                             ), false, false, array());
  212.                         }
  213.                         else{
  214.                             $db_dtype = CSaleDelivery::GetList(array(
  215.                                 "SORT" => "ASC",
  216.                                 "NAME" => "ASC"
  217.                             ), array("ACTIVE" => "Y",), false, false, array());
  218.                         }
  219.                     }
  220.                     else{
  221.                         $db_dtype = CSaleDelivery::GetList(array(
  222.                             "SORT" => "ASC",
  223.                             "NAME" => "ASC"
  224.                         ), array("ACTIVE" => "Y",), false, false, array());
  225.                     }
  226.                     //if ($ar_dtype = $db_dtype->Fetch()){
  227.                     while($ptype = $db_dtype->Fetch()){
  228.                         $arDelivery[$ptype['ID']] = $ptype;
  229.                     }
  230.                    
  231.                 }
  232.                
  233.             }
  234.             catch (Exception $e)
  235.             {
  236.                 $this->abortCache();
  237.                 throw $e;
  238.             }
  239.            
  240.             $this->endCache($arDelivery);
  241.            
  242.         }
  243.         else
  244.             $arDelivery = $this->getCacheData();
  245.        
  246.        
  247.         return $arDelivery;
  248.     }
  249.    
  250.     private function getUserFields(){
  251.         $arUserFields = $this->arParams['USER_DATA_FIELDS'];
  252.        
  253.        
  254.        
  255.         return $arUserFields;
  256.     }
  257.    
  258.     private function getUserFieldsRequire(){
  259.         if(is_array($this->arParams['USER_DATA_FIELDS_REQUIRED'])){                                        //Email only require
  260.             foreach($this->arParams['USER_DATA_FIELDS_REQUIRED'] as $require_field){            //Translator add fields marked settings
  261.                 $arUserFieldsRequire[$require_field] = 'Y';
  262.             }
  263.             return $arUserFieldsRequire;
  264.         }
  265.     }
  266.    
  267.     private function getOrderProps(){
  268.         if ($this->startCache(array('b1c-orderprops')))
  269.         {
  270.             try
  271.             {
  272.                 $arOrderProps = array();
  273.                 if(is_array($this->arParams['SHOW_PROPERTIES']) && !empty($this->arParams['SHOW_PROPERTIES'])){
  274.                     foreach($this->arParams['SHOW_PROPERTIES'] as $order_prop){
  275.                         $db_props = CSaleOrderProps::GetList(array("SORT" => "ASC"), array("ID" => $order_prop));
  276.                         if($arProps = $db_props->Fetch()){
  277.                             if($arProps['TYPE'] == 'SELECT' || $arProps['TYPE'] == 'MULTISELECT' || $arProps['TYPE'] == 'RADIO'){
  278.                                 $arProps['VALUE'] = array();
  279.                                 $db_vars = CSaleOrderPropsVariant::GetList(
  280.                                     array("SORT" => "ASC"),
  281.                                     array("ORDER_PROPS_ID" => $arProps["ID"])
  282.                                 );
  283.                                 while ($vars = $db_vars->Fetch())
  284.                                 {
  285.                                     $arProps['VALUE'][] = $vars;
  286.                                 }
  287.                             }
  288.                             $arOrderProps[] = $arProps;
  289.                         }
  290.                     }
  291.                    
  292.                 }
  293.                
  294.             }
  295.             catch (Exception $e)
  296.             {
  297.                 $this->abortCache();
  298.                 throw $e;
  299.             }
  300.            
  301.             $this->endCache($arOrderProps);
  302.            
  303.         }
  304.         else
  305.             $arOrderProps = $this->getCacheData();
  306.        
  307.        
  308.         return $arOrderProps;
  309.     }
  310.    
  311.     private function getOrderPropsRequire(){
  312.         if(is_array($this->arParams['SHOW_PROPERTIES_REQUIRED'])){
  313.             foreach($this->arParams['SHOW_PROPERTIES_REQUIRED'] as $require_props){            //Translator add fields marked settings
  314.                 $arOrderPropsRequire[$require_props] = 'Y';
  315.             }
  316.             return $arOrderPropsRequire;
  317.         }
  318.     }
  319.    
  320.     /**
  321.      * Функция запоминает поля заказа указанные пользователем при
  322.      * сбрасывании полей в форме
  323.      * @return string
  324.      */
  325.     private function getCurrentUserProps(){
  326.         $currentUserProps = array();
  327.         if(isset($this->requestData['ONECLICK_PROP'])){
  328.             foreach($this->requestData['ONECLICK_PROP'] as $id => $value){
  329.                 $prop = CSaleOrderProps::GetByID($id);
  330.                 $currentUserProps[$prop['CODE']] = $value;
  331.             }
  332.         }
  333.         return $currentUserProps;
  334.     }
  335.    
  336.     /*
  337.      * Функция запоминает обязательные поля заказа указанные пользователем при
  338.      * сбрасывании полей в форме
  339.      */
  340.     private function getCurrentUser(){
  341.         global $USER;
  342.         $user_id = $USER->GetID();
  343.        
  344.         if(intval($user_id) > 0){
  345.             $rsUser = CUser::GetByID(intval($user_id));
  346.             $currentUser = $rsUser->Fetch();
  347.         }else{
  348.             $currentUser = array();
  349.         }
  350.         /** проверка поста */
  351.         if(isset($this->requestData['ONECLICK'])) {
  352.             foreach ($this->requestData['ONECLICK'] as $key => $value) {
  353.                 $currentUser[$key] = $value;
  354.             }
  355.         }
  356.         return $currentUser;
  357.     }
  358.    
  359.    
  360.     /**
  361.      * Функция для получения цены, либо его торговых предложений, если они есть
  362.      *
  363.      * @param $ELEMENT_ID int ид элемента
  364.      * @param $arPriceCode array Массив типов цен
  365.      * @param $type_price string какое значение цены возвращать
  366.      * @param $USER_ID int Ид пользователя
  367.      * @param $SITE_ID int Ид сайта
  368.      * @param $floor bool Округлять цену
  369.      *
  370.      * @return float|bool|string
  371.      */
  372.     private function GetPriceProduct(
  373.         $ELEMENT_ID,
  374.         $arPriceCode = array(),
  375.         $type_price = "DISCOUNT_VALUE",
  376.         $USER_ID = 1,
  377.         $SITE_ID = false,
  378.         $floor = false)
  379.     {
  380.         if(!$SITE_ID){
  381.             $SITE_ID = SITE_ID;
  382.         }
  383.         if(!\Bitrix\Main\Loader::IncludeModule("iblock"))
  384.             return false;
  385.         $ELEMENT_ID = intVal($ELEMENT_ID);
  386.         if($ELEMENT_ID <= 0){
  387.             return false;
  388.         }
  389.         $res = CIBlockElement::GetByID($ELEMENT_ID);
  390.         if($ar_res = $res->GetNext()){
  391.             $arElement = $ar_res;
  392.         }else{
  393.             return false;
  394.         }
  395.         if(empty($arPriceCode)){
  396.             $arBasePrice = \CCatalogGroup::GetBaseGroup();
  397.             if(is_array($arBasePrice) && !empty($arBasePrice))
  398.                 $arPriceCode = array($arBasePrice['NAME']);
  399.             else
  400.                 return false;
  401.         }
  402.        
  403.         if(!is_array($arPriceCode)){
  404.             $arPriceCode = array($arPriceCode);
  405.         }
  406.        
  407.         $arResultPrices = \CIBlockPriceTools::GetCatalogPrices($arElement["IBLOCK_ID"], $arPriceCode);
  408.         $arSelectProperties = (is_array($this->arParams['LIST_OFFERS_PROPERTY_CODE']) && !empty($this->arParams['LIST_OFFERS_PROPERTY_CODE']))?$this->arParams['LIST_OFFERS_PROPERTY_CODE']:array();
  409.         $arOffers = \CIBlockPriceTools::GetOffersArray(
  410.             array(
  411.                 'IBLOCK_ID' => $arElement["IBLOCK_ID"],
  412.                 'HIDE_NOT_AVAILABLE' => 'Y',
  413.             )                       //arFilter
  414.             ,array($ELEMENT_ID)     //arElementID
  415.             ,array()                //arOrder
  416.             ,array()                //arSelectFields
  417.             ,$arSelectProperties    //arSelectProperties
  418.             ,0                      //limit
  419.             ,$arResultPrices        //arPrices
  420.             ,true                   //vat_include
  421.             ,array()                //arCurencyParams
  422.             ,$USER_ID               //USER_ID
  423.             ,$SITE_ID               //SITE_ID
  424.        
  425.         );
  426.        
  427.         if(!empty($arOffers)){
  428.            
  429.             return 'OFFERS';
  430.         }
  431.         $arSelect = array(
  432.             "ID",
  433.             "IBLOCK_ID",
  434.             "CODE",
  435.             "XML_ID",
  436.             "NAME",
  437.             "ACTIVE",
  438.             "DATE_ACTIVE_FROM",
  439.             "DATE_ACTIVE_TO",
  440.             "SORT",
  441.             "PREVIEW_TEXT",
  442.             "PREVIEW_TEXT_TYPE",
  443.             "DETAIL_TEXT",
  444.             "DETAIL_TEXT_TYPE",
  445.             "DATE_CREATE",
  446.             "CREATED_BY",
  447.             "TIMESTAMP_X",
  448.             "MODIFIED_BY",
  449.             "TAGS",
  450.             "IBLOCK_SECTION_ID",
  451.             "DETAIL_PAGE_URL",
  452.             "LIST_PAGE_URL",
  453.             "DETAIL_PICTURE",
  454.             "PREVIEW_PICTURE",
  455.             "PROPERTY_*",
  456.         );
  457.        
  458.         foreach($arResultPrices as &$value)
  459.         {
  460.             if (!$value['CAN_VIEW'] && !$value['CAN_BUY'])
  461.                 continue;
  462.             $arSelect[] = $value["SELECT"];
  463.         }
  464.        
  465.         if (isset($value))
  466.             unset($value);
  467.         $res = \CIBlockElement::GetList(Array(), array("ID" => $ELEMENT_ID), false, false, $arSelect);
  468.         if($ob = $res->GetNextElement()){
  469.             $arElement = $ob->GetFields();
  470.            
  471.         }
  472.         $arElement["CAT_PRICES"] = $arResultPrices;
  473.         $arPrice = \CIBlockPriceTools::GetItemPrices($arElement["IBLOCK_ID"], $arResultPrices, $arElement, true, array(), $USER_ID, $SITE_ID);
  474.         if (!empty($arPrice))
  475.         {
  476.             $min_price = false;
  477.             $currency = false;
  478.             foreach($arPrice as $code_price => $price){
  479.                 if(!$min_price || $price[$type_price] < $min_price){
  480.                     $min_price = $price[$type_price];
  481.                     $currency = $price['CURRENCY'];
  482.                 }
  483.             }
  484.            
  485.         }
  486.         if($floor && $min_price){
  487.             $min_price = floor($min_price/$floor)*$floor;
  488.         }
  489.         $quantity = $this->arResult['QUANTITY'] > 0 ? $this->arResult['QUANTITY'] : 1;
  490.         if($min_price){
  491.             return array(
  492.                 "PRICE" => $min_price * $quantity,
  493.                 "CURRENCY" => $currency
  494.             );
  495.         }
  496.         return $min_price;
  497.     }
  498.    
  499.    
  500.    
  501.     /**
  502.      * Функция выводит при заказе название товара, цену и количество
  503.      */
  504.     private function getCurrentProduct($element_id, $quantity = 1)
  505.     {
  506.         if ($this->startCache(array('b1c-curentproduct-'.$element_id)))
  507.         {
  508.             try
  509.             {
  510.                 $prod_fields = CIBlockElement::GetByID($element_id);
  511.                 $result = array();
  512.                 if ($arItem = $prod_fields->Fetch()) {
  513.                     $result["FIELDS"] = $arItem['NAME'];
  514.                     if($this->arParams["SHOW_OFFERS_FIRST_STEP"] != 'Y'){
  515.                         $result['OFFERS'] = array();
  516.                         $result['OFFERS'] = $this->getOffers($element_id);
  517.                     }
  518.                     $min_price = $this->GetPriceProduct($element_id, $this->arParams['PRICE_CODE'], "DISCOUNT_VALUE", $this->userID, SITE_ID);
  519.                     if($min_price == 'OFFERS'){
  520.                         if(!empty($this->arOffers)) {
  521.                             $result['OFFERS'] = array();
  522.                             $offerID_min_price = 0;
  523.                             $offer_min_price = false;
  524.                             foreach ($this->arOffers as $arOffer) {
  525.                                 $result['OFFERS'][$arOffer['ID']] = $this->GetPriceProduct($arOffer['ID'], $this->arParams['PRICE_CODE'], "DISCOUNT_VALUE", $this->userID, SITE_ID);    //получаем массив цен торговых предложений
  526.                                 if(is_array($result['OFFERS'][$arOffer['ID']])){
  527.                                     if(!$offer_min_price){
  528.                                         $offer_min_price = $result['OFFERS'][$arOffer['ID']]['PRICE'];
  529.                                         $offerID_min_price = $arOffer['ID'];
  530.                                     }elseif($offer_min_price > $result['OFFERS'][$arOffer['ID']]['PRICE']){
  531.                                         $offer_min_price = $result['OFFERS'][$arOffer['ID']]['PRICE'];
  532.                                         $offerID_min_price = $arOffer['ID'];
  533.                                     }
  534.                                 }
  535.                             }
  536.                             $result['OFFER_ID_MIN_PRICE'] = $offerID_min_price;
  537.                            
  538.                         }
  539.                     }else{
  540.                         $result["PRICE"] = $min_price;        // получаем цену товара без торговых предложений
  541.                     }
  542.                 }
  543.                
  544.             }
  545.             catch (Exception $e)
  546.             {
  547.                 $this->abortCache();
  548.                 throw $e;
  549.             }
  550.            
  551.             $this->endCache($result);
  552.            
  553.         }
  554.         else
  555.             $result = $this->getCacheData();
  556.        
  557.        
  558.        
  559.         return $result;
  560.     }
  561.    
  562.     private function verifyFields($reqFields = array(), $reqFieldsProps = array()){
  563.         $errors = array();
  564.         if(is_array($this->requestData['ONECLICK'])){
  565.             foreach($this->requestData['ONECLICK'] as $user_fields => $value){
  566.                 if($reqFields[$user_fields] == 'Y' && $value == ''){
  567.                     $errors[$user_fields] = 'Y';
  568.                 }
  569.                 if($user_fields == 'EMAIL'){
  570.                     if(!filter_var($value, FILTER_VALIDATE_EMAIL)){
  571.                         $errors[$user_fields] = 'EMAIL';
  572.                     }
  573.                 }
  574.             }
  575.         }
  576.        
  577.         if(is_array($this->requestData['ONECLICK_PROP'])){
  578.             foreach($this->requestData['ONECLICK_PROP'] as $order_prop => $value_prop){
  579.                 $arProp_db = \CSaleOrderProps::GetList(array(), array('ID' => $order_prop));
  580.                 if($arProp = $arProp_db->fetch()){
  581.                     if($arProp['IS_EMAIL'] == 'Y'){
  582.                         if(!filter_var($value_prop, FILTER_VALIDATE_EMAIL)){
  583.                             $errors[$order_prop] = 'EMAIL';
  584.                         }
  585.                     }
  586.                     /** Проверка местополжения */
  587.                     if($arProp['TYPE'] == 'LOCATION' && $value_prop != ""){
  588.                         if($item = \Bitrix\Sale\Location\LocationTable::getById($value_prop)->fetch()){
  589.                             $this->requestData['ONECLICK_PROP'][$order_prop] = $item['CODE'];
  590.                         }else{
  591.                             $errors[$order_prop] = 'Y';
  592.                         }
  593.                        
  594.                     }
  595.                 }
  596.                 if($reqFieldsProps[$order_prop] == 'Y' && $value_prop == ''){
  597.                     $errors[$order_prop] = 'Y';
  598.                 }
  599.                
  600.             }
  601.         }
  602.        
  603.         if($this->show_captha /*&& strlen($this->requestData['captcha_sid']) > 0 && $this->requestData['offers'] != "Y"*/){
  604.             include_once($_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/classes/general/captcha.php");
  605.             $captcha_code = $this->requestData["captcha_sid"];
  606.             $captcha_word = $this->requestData["captcha_word"];
  607.             $cpt = new CCaptcha();
  608.             $captchaPass = COption::GetOptionString("main", "captcha_password", "");
  609.             if(strlen($captcha_word) > 0 && strlen($captcha_code) > 0){
  610.                 if(!$cpt->CheckCodeCrypt($captcha_word, $captcha_code, $captchaPass))
  611.                     $errors['CAPTCHA'] = Loc::getMessage("MF_CAPTCHA_WRONG");
  612.             }else
  613.                 $errors["CAPTCHA"] = Loc::getMessage("MF_CAPTHCA_EMPTY");
  614.            
  615.         }elseif($this->show_captha && $this->requestData['offers'] != "Y"){
  616.             $errors["CAPTCHA"] = Loc::getMessage("MF_CAPTHCA_EMPTY");
  617.         }
  618.         return $errors;
  619.     }
  620.    
  621.     /**
  622.      * Проверка подключенных модулей
  623.      * @throws \Main\SystemException
  624.      */
  625.     protected function checkRequiredModules(){
  626.         if(!Loader::includeModule('h2o.buyoneclick'))
  627.             throw new Main\SystemException(Loc::getMessage("H2O_MODULE_NOT_INSTALL"));
  628.         if(!Loader::includeModule('iblock'))
  629.             throw new Main\SystemException(Loc::getMessage("IBLOCK_MODULE_NOT_INSTALL"));
  630.         if(!Loader::includeModule('sale'))
  631.             throw new Main\SystemException(Loc::getMessage("SALE_MODULE_NOT_INSTALL"));
  632.         if(!Loader::includeModule('catalog'))
  633.             throw new Main\SystemException(Loc::getMessage("CATALOG_MODULE_NOT_INSTALL"));
  634.        
  635.     }
  636.    
  637.     /**
  638.      * Обработка $_REQUEST
  639.      */
  640.     protected function processRequest(){
  641.         global $APPLICATION;
  642.         $this->requestData = $APPLICATION->ConvertCharsetArray($_REQUEST, 'UTF-8', LANG_CHARSET);    //ajax запросы отправляются в UTF-8
  643.         /** @var  needGetData bool
  644.          * Получать ли данные
  645.          * !!!
  646.          * Скрытый параметр IS_POPUP_TEMPLATE, если равен Y,
  647.          * то данные при загрузке страницы не получаются.
  648.          * Нужен для кастомизации шаблонов.
  649.          * Скрытый потому, чтобы не путать людей
  650.          */
  651.         $this->needGetData = (
  652.                 ($this->templateName != '.default' || $this->templateName != '') &&
  653.                 $this->arParams['IS_POPUP_TEMPLATE'] != 'Y') ||
  654.             $this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == $this->ajax_id ||
  655.             $this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == "Y";
  656.     }
  657.    
  658.     /**
  659.      * Function wraps action list evaluation into try-catch block.
  660.      * @return void
  661.      */
  662.     private function performActions(){
  663.         if(class_exists("Bitrix\Sale\Compatible\DiscountCompatibility") &&
  664.             method_exists("Bitrix\Sale\Compatible\DiscountCompatibility", "stopUsageCompatible")){
  665.             Sale\Compatible\DiscountCompatibility::stopUsageCompatible();
  666.         }
  667.         try{
  668.             $this->performActionList();
  669.         }catch(Exception $e){
  670.             $this->errorsNonFatal[htmlspecialcharsEx($e->getCode())] = htmlspecialcharsEx($e->getMessage());
  671.         }
  672.         if(class_exists("Bitrix\Sale\Compatible\DiscountCompatibility") &&
  673.             method_exists("Bitrix\Sale\Compatible\DiscountCompatibility", "revertUsageCompatible")){
  674.             Sale\Compatible\DiscountCompatibility::revertUsageCompatible();
  675.         }
  676.     }
  677.    
  678.     /**
  679.      * Function perform pre-defined list of actions based on current state of $_REQUEST and parameters.
  680.      * @return void
  681.      */
  682.     protected function performActionList(){
  683.         // add order
  684.         $this->performActionBuy();
  685.        
  686.         // some other ...
  687.     }
  688.    
  689.     /**
  690.      * Perform the following action: add order
  691.      * @throws Main\SystemException
  692.      * @return void
  693.      */
  694.     protected function performActionBuy(){
  695.         if($this->requestData['buy_one_click'] == 'Y' && !isset($this->arResult['FATAL_ERROR']) && ($this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == $this->ajax_id || $this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == 'Y')){
  696.             $this->addNewOrder();
  697.         }
  698.     }
  699.    
  700.     protected function getOffers($ELEMENT_ID){
  701.         if(intval($ELEMENT_ID) <= 0){
  702.             return false;
  703.         }
  704.         $res = Bitrix\Iblock\ElementTable::getById($ELEMENT_ID);
  705.         $arElement = $res->fetch();
  706.        
  707.         $arResultPrices = \CIBlockPriceTools::GetCatalogPrices($arElement["IBLOCK_ID"], $this->arParams['PRICE_CODE']);
  708.        
  709.         $arSelectProperties = (is_array($this->arParams['LIST_OFFERS_PROPERTY_CODE']) && !empty($this->arParams['LIST_OFFERS_PROPERTY_CODE']))?$this->arParams['LIST_OFFERS_PROPERTY_CODE']:array();
  710.        
  711.         $arOffers = \CIBlockPriceTools::GetOffersArray(
  712.             array(
  713.                 'IBLOCK_ID' => $arElement["IBLOCK_ID"],
  714.                 'HIDE_NOT_AVAILABLE' => 'Y',
  715.             )                       //arFilter
  716.             ,array($ELEMENT_ID)     //arElementID
  717.             ,array()                //arOrder
  718.             ,array()                //arSelectFields
  719.             ,$arSelectProperties    //arSelectProperties
  720.             ,0                      //limit
  721.             ,$arResultPrices        //arPrices
  722.             ,true                   //vat_include
  723.             ,array()                //arCurencyParams
  724.        
  725.         );
  726.        
  727.         $this->arOffers = $arOffers;
  728.         return $arOffers;
  729.     }
  730.    
  731.     /**
  732.      * @param $order_id
  733.      * Функция для установки глобальных переменных, необходимых для платежных систем
  734.      */
  735.     protected function setOrderValueForPaySystem($order_id){
  736.         $db_sales = \CSaleOrder::GetList(array("DATE_INSERT" => "ASC"), array("ID" => $order_id));
  737.         if ($arOrder = $db_sales->Fetch())
  738.         {
  739.             if(!isset($GLOBALS["SALE_CORRESPONDENCE"])){
  740.                 $GLOBALS["SALE_CORRESPONDENCE"] = array(
  741.                     "AMOUNT" => array(),
  742.                     "CURRENCY" => array(),
  743.                     "ORDER_ID" => array()
  744.                 );
  745.             }
  746.             if(!isset($GLOBALS["SALE_INPUT_PARAMS"])){
  747.                 $GLOBALS["SALE_INPUT_PARAMS"] = array(
  748.                     "ORDER" => array()
  749.                 );
  750.             }
  751.             if(!isset($GLOBALS["SALE_CORRESPONDENCE"]["AMOUNT"]["VALUE"]) || $GLOBALS["SALE_CORRESPONDENCE"]["AMOUNT"]["VALUE"] == 0){
  752.                 $GLOBALS["SALE_CORRESPONDENCE"]["AMOUNT"]["VALUE"] = $arOrder['PRICE'];
  753.             }
  754.             if(!isset($GLOBALS['SALE_INPUT_PARAMS']['ORDER']['SHOULD_PAY']) || $GLOBALS['SALE_INPUT_PARAMS']['ORDER']['SHOULD_PAY'] == 0){
  755.                 $GLOBALS['SALE_INPUT_PARAMS']['ORDER']['SHOULD_PAY'] = $arOrder['PRICE'];
  756.             }
  757.             if(!isset($GLOBALS["SALE_CORRESPONDENCE"]["CURRENCY"]["VALUE"])){
  758.                 $GLOBALS["SALE_CORRESPONDENCE"]["CURRENCY"]["VALUE"] = $arOrder['CURRENCY'];
  759.             }
  760.             if(!isset($GLOBALS['SALE_INPUT_PARAMS']['ORDER']['CURRENCY'])){
  761.                 $GLOBALS['SALE_INPUT_PARAMS']['ORDER']['CURRENCY'] = $arOrder['CURRENCY'];
  762.             }
  763.             if(!isset($GLOBALS["SALE_CORRESPONDENCE"]["ORDER_ID"]["VALUE"])){
  764.                 $GLOBALS["SALE_CORRESPONDENCE"]["ORDER_ID"]["VALUE"] = $arOrder['ACCOUNT_NUMBER'];
  765.             }
  766.             if(!isset($GLOBALS['SALE_INPUT_PARAMS']['ORDER']['ID'])){
  767.                 $GLOBALS['SALE_INPUT_PARAMS']['ORDER']['ID'] = $arOrder['ACCOUNT_NUMBER'];
  768.             }
  769.         }
  770.     }
  771.    
  772.     protected function addNewOrder(){
  773.         $this->arResult['ERRORS'] = $this->verifyFields($this->arResult['USER_FIELDS_REQUIRED'], $this->arResult['SHOW_PROPERTIES_REQUIRED']);
  774.         if(empty($this->arResult['ERRORS'])){
  775.             if($this->arParams["USE_OLD_CLASS"] != 'Y'){
  776.                 $class = new \h2o\buyoneclick\orderD7($this->element_id, $this->requestData['ONECLICK'], $this->requestData['ONECLICK_PROP'], $this->arParams);
  777.             }else{
  778.                 $class = new h2o\buyoneclick\h2obuyoneclick($this->element_id, $this->requestData['ONECLICK'], $this->requestData['ONECLICK_PROP'], $this->arParams);
  779.             }
  780.            
  781.            
  782.             if(is_array($this->arParams['NEW_USER_GROUP_ID']) && !empty($this->arParams['NEW_USER_GROUP_ID'])){
  783.                 $class->SetNewUserGroupId($this->arParams['NEW_USER_GROUP_ID']);
  784.             }else{
  785.                 $def_group = COption::GetOptionString("main", "new_user_registration_def_group", "");
  786.                 $class->SetNewUserGroupId(explode(",", $def_group));
  787.             }
  788.            
  789.             if($this->arParams["SHOW_QUANTITY"] || floatval($this->requestData['quantity_b1c']) > 0){
  790.                 $class->SetQuantity($this->requestData['quantity_b1c']);
  791.             }else{
  792.                 $class->SetQuantity(1);
  793.             }
  794.            
  795.             if($this->arParams['ADD_NOT_AUTH_TO_ONE_USER']){
  796.                 $class->setFixUser($this->arParams['ADD_NOT_AUTH_TO_ONE_USER_ID']);
  797.             }
  798.            
  799.             if($this->arParams['PERSON_TYPE_ID'] > 0){
  800.                 $class->SetPERSON_TYPE_ID($this->arParams['PERSON_TYPE_ID']);
  801.             }else{
  802.                 $db_ptype = \CSalePersonType::GetList(Array("SORT" => "ASC"), Array("ACTIVE" => "Y"));
  803.                 if($ptype = $db_ptype->Fetch()){
  804.                     $def_person_type_id = $ptype['ID'];
  805.                 }else{
  806.                     throw new Main\SystemException(Loc::getMessage("NOT_FOUND_GROUP_ID"));
  807.                 }
  808.                 $class->SetPERSON_TYPE_ID($def_person_type_id);
  809.             }
  810.            
  811.            
  812.             if($this->arParams['SHOW_PAY_SYSTEM'] && $this->requestData['PAY_SYSTEM'] > 0){
  813.                 $class->SetPAY_SYSTEM_ID($this->requestData['PAY_SYSTEM']);
  814.             }else{
  815.                 $find_paysystem = false;
  816.                 if($this->arParams['DEFAULT_PAY_SYSTEM'] != ""){
  817.                     $db_ptype = \CSalePaySystem::GetList($arOrder = Array("ID"=>"ASC", "PSA_NAME"=>"ASC"), Array("ID"=>$this->arParams['DEFAULT_PAY_SYSTEM']));
  818.                     if ($ptype = $db_ptype->Fetch())
  819.                     {
  820.                         $class->SetPAY_SYSTEM_ID($ptype["ID"]);
  821.                         $find_paysystem = true;
  822.                     }
  823.                 }
  824.                 if(!$find_paysystem){
  825.                     $db_ptype = \CSalePaySystem::GetList($arOrder = Array(
  826.                         "ID" => "ASC",
  827.                         "PSA_NAME" => "ASC"
  828.                     ), Array("ACTIVE" => "Y"));
  829.                     if($ptype = $db_ptype->Fetch()){
  830.                         $class->SetPAY_SYSTEM_ID($ptype["ID"]);
  831.                     }
  832.                 }
  833.             }
  834.            
  835.             if($this->arParams['SHOW_USER_DESCRIPTION'] && strlen($this->requestData['ONECLICK_COMMENT']) > 0){
  836.                 $class->SetUserDescription($this->requestData['ONECLICK_COMMENT']);
  837.             }
  838.            
  839.             if($this->arParams['SHOW_DELIVERY'] && $this->requestData['DELIVERY'] > 0){
  840.                 $class->SetDELIVERY_ID($this->requestData['DELIVERY']);
  841.                 $class->SetPRICE_DELIVERY($this->arResult['DELIVERY'][$this->requestData['DELIVERY']]['PRICE']);
  842.             }else{
  843.                 $find_delivery = false;
  844.                 if($this->arParams['DEFAULT_DELIVERY'] != ""){
  845.                     if(class_exists("Bitrix\Sale\Delivery\Services\Table") && method_exists("Bitrix\Sale\Delivery\Services\Table", "getById")){
  846.                         $dbDelivery = Delivery\Services\Table::getById($this->arParams['DEFAULT_DELIVERY']);
  847.                         if($delivery = $dbDelivery->fetch()){
  848.                             $class->SetDELIVERY_ID($delivery['ID']);
  849.                             $class->SetPRICE_DELIVERY(0);
  850.                             $find_delivery = true;
  851.                         }
  852.                     }else{
  853.                         $db_dtype = CSaleDelivery::GetList($arOrder = Array("ID" => "ASC"),
  854.                             array("ID" => $this->arParams['DEFAULT_DELIVERY']));
  855.                         if($delivery = $db_dtype->Fetch()){
  856.                             $class->SetDELIVERY_ID($delivery['ID']);
  857.                             $class->SetPRICE_DELIVERY($delivery['PRICE']);
  858.                             $find_delivery = true;
  859.                         }
  860.                     }
  861.                 }
  862.                 if(!$find_delivery){
  863.                     /** Устанавливаем !!!БЕСПЛАТНУЮ!!!(если бесплатной нет - то все плохо:)) доставку, без нее не будет резервирования товара! */
  864.                     $db_dtype = CSaleDelivery::GetList($arOrder = Array("ID" => "ASC"), array("ACTIVE" => "Y"));
  865.                     while($delivery = $db_dtype->Fetch()){
  866.                         if($delivery['PRICE'] > 0){
  867.                             continue;
  868.                         }
  869.                         $class->SetDELIVERY_ID($delivery['ID']);
  870.                         break;
  871.                     }
  872.                 }
  873.             }
  874.            
  875.             if(is_array($this->arParams['PRICE_CODE'])){
  876.                 $class->SetPriceCode($this->arParams['PRICE_CODE']);
  877.             }
  878.            
  879.             if($this->arParams['BUY_CURRENT_BASKET']){
  880.                 $class->BuyCurrentBasketMode(true);
  881.             }
  882.            
  883.             $return = $class->Buy();
  884.            
  885.             if($this->arParams['USE_OLD_CLASS'] != "Y"){
  886.                 if(!empty($return['OFFERS'])){
  887.                     $this->arResult['OFFERS'] = $return['OFFERS'];
  888.                     if($this->arParams["SHOW_QUANTITY"] || floatval($this->requestData['quantity_b1c']) > 0){
  889.                         /** передаем количество*/
  890.                         $this->arResult["QUANTITY"] = $this->requestData['quantity_b1c'];
  891.                     }
  892.                 }
  893.                 if(isset($return['WARNING'])){
  894.                     $this->errorsNonFatal = array_merge($this->errorsNonFatal, $return['WARNING']);
  895.                 }
  896.                 $this->arResult['ORDER_ID'] = $return['ORDER_ID'];
  897.                 $this->arResult['SUCCESS'] = $return['ACCOUNT_NUMBER'];
  898.                 //if($this->arParams['MODE_EXTENDED'] == 'Y' && $this->arParams['SHOW_PAY_SYSTEM'] && $this->requestData['PAY_SYSTEM'] > 0){
  899.                 $dbPaySysAction = CSalePaySystemAction::GetList(array(), array(
  900.                     "PAY_SYSTEM_ID" => $class->GetPaySystemId(),
  901.                     "PERSON_TYPE_ID" => $class->GetPersonTypeId()
  902.                 ), false, false, array(
  903.                     "NAME",
  904.                     "ACTION_FILE",
  905.                     "NEW_WINDOW",
  906.                     "PARAMS",
  907.                     "ENCODING",
  908.                     "LOGOTIP"
  909.                 ));
  910.                 //$this->setOrderValueForPaySystem($return['ORDER_ID']);
  911.                 \CSalePaySystemAction::InitParamArrays(false, $return['ORDER_ID']);
  912.                 if($arPaySysAction = $dbPaySysAction->Fetch()){
  913.                     $arPaySysAction["NAME"] = htmlspecialcharsEx($arPaySysAction["NAME"]);
  914.                     if(strlen($arPaySysAction["ACTION_FILE"]) > 0){
  915.                         if($arPaySysAction["NEW_WINDOW"] != "Y"){
  916.                             CSalePaySystemAction::InitParamArrays(false, $return['ORDER_ID'], $arPaySysAction["PARAMS"]);
  917.                            
  918.                             $pathToAction = $_SERVER["DOCUMENT_ROOT"] . $arPaySysAction["ACTION_FILE"];
  919.                            
  920.                             $pathToAction = str_replace("\\", "/", $pathToAction);
  921.                             while(substr($pathToAction, strlen($pathToAction) - 1, 1) == "/")
  922.                                 $pathToAction = substr($pathToAction, 0, strlen($pathToAction) - 1);
  923.                            
  924.                             if(file_exists($pathToAction)){
  925.                                 if(is_dir($pathToAction) && file_exists($pathToAction . "/payment.php"))
  926.                                     $pathToAction .= "/payment.php";
  927.                                
  928.                                 $arPaySysAction["PATH_TO_ACTION"] = $pathToAction;
  929.                             }
  930.                            
  931.                             if(strlen($arPaySysAction["ENCODING"]) > 0){
  932.                                 define("BX_SALE_ENCODING", $arPaySysAction["ENCODING"]);
  933.                                 AddEventHandler("main", "OnEndBufferContent", "ChangeEncoding");
  934.                                 function ChangeEncoding(&$content){
  935.                                     global $APPLICATION;
  936.                                     header("Content-Type: text/html; charset=" . BX_SALE_ENCODING);
  937.                                     $content = $APPLICATION->ConvertCharset($content, SITE_CHARSET, BX_SALE_ENCODING);
  938.                                     $content = str_replace("charset=" . SITE_CHARSET, "charset=" . BX_SALE_ENCODING, $content);
  939.                                 }
  940.                             }
  941.                         }
  942.                     }
  943.                    
  944.                     if($arPaySysAction > 0)
  945.                         $arPaySysAction["LOGOTIP"] = CFile::GetFileArray($arPaySysAction["LOGOTIP"]);
  946.                    
  947.                     $this->arResult["PAY_SYSTEM"] = $arPaySysAction;
  948.                 }
  949.                 //}
  950.             }else{
  951.                 if(is_array($return)){
  952.                     if($return['ERROR'] != ""){
  953.                         throw new Main\SystemException($return['ERROR']);
  954.                     }
  955.                     elseif(!empty($return['OFFERS'])){
  956.                         $this->arResult['OFFERS'] = $return['OFFERS'];
  957.                         if($this->arParams["SHOW_QUANTITY"]){
  958.                             /** передаем количество*/
  959.                             $this->arResult["QUANTITY"] = $this->requestData['quantity_b1c'];
  960.                         }
  961.                     }
  962.                     else{
  963.                         throw new Main\SystemException(implode(";", $return));
  964.                     }
  965.                 }
  966.                 else{
  967.                     global $APPLICATION;
  968.                     $APPLICATION->RestartBuffer();
  969.                     $this->arResult['SUCCESS'] = $return;
  970.                     if($this->arParams['MODE_EXTENDED'] == 'Y' && $this->arParams['SHOW_PAY_SYSTEM'] && $this->requestData['PAY_SYSTEM'] > 0){
  971.                         $dbPaySysAction = CSalePaySystemAction::GetList(array(), array(
  972.                             "PAY_SYSTEM_ID" => $class->GetPaySystemId(),
  973.                             "PERSON_TYPE_ID" => $class->GetPersonTypeId()
  974.                         ), false, false, array(
  975.                             "NAME",
  976.                             "ACTION_FILE",
  977.                             "NEW_WINDOW",
  978.                             "PARAMS",
  979.                             "ENCODING",
  980.                             "LOGOTIP"
  981.                         ));
  982.                         if($arPaySysAction = $dbPaySysAction->Fetch()){
  983.                             $arPaySysAction["NAME"] = htmlspecialcharsEx($arPaySysAction["NAME"]);
  984.                             if(strlen($arPaySysAction["ACTION_FILE"]) > 0){
  985.                                 if($arPaySysAction["NEW_WINDOW"] != "Y"){
  986.                                     CSalePaySystemAction::InitParamArrays(false, $return, $arPaySysAction["PARAMS"]);
  987.                                    
  988.                                     $pathToAction = $_SERVER["DOCUMENT_ROOT"] . $arPaySysAction["ACTION_FILE"];
  989.                                    
  990.                                     $pathToAction = str_replace("\\", "/", $pathToAction);
  991.                                     while(substr($pathToAction, strlen($pathToAction) - 1, 1) == "/")
  992.                                         $pathToAction = substr($pathToAction, 0, strlen($pathToAction) - 1);
  993.                                    
  994.                                     if(file_exists($pathToAction)){
  995.                                         if(is_dir($pathToAction) && file_exists($pathToAction . "/payment.php"))
  996.                                             $pathToAction .= "/payment.php";
  997.                                        
  998.                                         $arPaySysAction["PATH_TO_ACTION"] = $pathToAction;
  999.                                     }
  1000.                                    
  1001.                                     if(strlen($arPaySysAction["ENCODING"]) > 0){
  1002.                                         define("BX_SALE_ENCODING", $arPaySysAction["ENCODING"]);
  1003.                                         AddEventHandler("main", "OnEndBufferContent", "ChangeEncoding");
  1004.                                         function ChangeEncoding(&$content){
  1005.                                             global $APPLICATION;
  1006.                                             header("Content-Type: text/html; charset=" . BX_SALE_ENCODING);
  1007.                                             $content = $APPLICATION->ConvertCharset($content, SITE_CHARSET, BX_SALE_ENCODING);
  1008.                                             $content = str_replace("charset=" . SITE_CHARSET, "charset=" . BX_SALE_ENCODING, $content);
  1009.                                         }
  1010.                                     }
  1011.                                 }
  1012.                             }
  1013.                            
  1014.                             if($arPaySysAction > 0)
  1015.                                 $arPaySysAction["LOGOTIP"] = CFile::GetFileArray($arPaySysAction["LOGOTIP"]);
  1016.                            
  1017.                             $this->arResult["PAY_SYSTEM"] = $arPaySysAction;
  1018.                         }
  1019.                     }
  1020.                 }
  1021.             }
  1022.         }
  1023.     }
  1024.    
  1025.     /**
  1026.      * Получение ajaxID
  1027.      * @return string
  1028.      */
  1029.     protected function getAjaxID() {
  1030.         global $DB;
  1031.        
  1032.         $ajax_call_id = md5($this->getName()."|".$this->GetTemplateName()."|".serialize($this->arParams)."|".COption::GetOptionString("main", "server_uniq_id", $_SERVER['SERVER_NAME']));
  1033.        
  1034.         return $ajax_call_id;
  1035.     }
  1036.    
  1037.     /**
  1038.      * Обработка ошибок
  1039.      */
  1040.     protected function formatResultErrors(){
  1041.         $errors = array();
  1042.         if(!empty($this->errorsFatal))
  1043.             $errors['FATAL'] = $this->errorsFatal;
  1044.         if(!empty($this->errorsNonFatal))
  1045.             $errors['NONFATAL'] = $this->errorsNonFatal;
  1046.        
  1047.        
  1048.         if(!empty($errors['FATAL']))
  1049.             $this->arResult['FATAL_ERROR'] = $errors['FATAL'];
  1050.         if(!empty($errors['NONFATAL']))
  1051.             $this->arResult['ERROR_STRING'] = $errors['NONFATAL'];
  1052.        
  1053.         // backward compatiblity
  1054.         $error = each($this->errorsFatal);
  1055.         if(!empty($error['value']))
  1056.             $this->arResult['ERROR_MESSAGE'] = $error['value'];
  1057.     }
  1058.    
  1059.     ////////////////////////
  1060.     // Cache functions
  1061.     ////////////////////////
  1062.     /**
  1063.      * Function checks if cacheing is enabled in component parameters
  1064.      * @return boolean
  1065.      */
  1066.     final protected function getCacheNeed()
  1067.     {
  1068.         return  intval($this->arParams['CACHE_TIME']) > 0 &&
  1069.         $this->arParams['CACHE_TYPE'] != 'N' &&
  1070.         Config\Option::get("main", "component_cache_on", "Y") == "Y";
  1071.     }
  1072.    
  1073.     /**
  1074.      * Function perform start of cache process, if needed
  1075.      * @param mixed[]|string $cacheId An optional addition for cache key
  1076.      * @return boolean True, if cache content needs to be generated, false if cache is valid and can be read
  1077.      */
  1078.     final protected function startCache($cacheId = array())
  1079.     {
  1080.         if(!$this->getCacheNeed())
  1081.             return true;
  1082.        
  1083.         $this->currentCache = Data\Cache::createInstance();
  1084.        
  1085.         return $this->currentCache->startDataCache(intval($this->arParams['CACHE_TIME']), $this->getCacheKey($cacheId), "/", array(), "cache/h2o");
  1086.     }
  1087.    
  1088.     /**
  1089.      * Function perform start of cache process, if needed
  1090.      * @throws Main\SystemException
  1091.      * @param mixed[] $data Data to be stored in the cache
  1092.      * @return void
  1093.      */
  1094.     final protected function endCache($data = false)
  1095.     {
  1096.         if(!$this->getCacheNeed())
  1097.             return;
  1098.        
  1099.         if($this->currentCache == 'null')
  1100.             throw new Main\SystemException('Cache were not started');
  1101.        
  1102.         $this->currentCache->endDataCache($data);
  1103.         $this->currentCache = null;
  1104.     }
  1105.    
  1106.     /**
  1107.      * Function discard cache generation
  1108.      * @throws Main\SystemException
  1109.      * @return void
  1110.      */
  1111.     final protected function abortCache()
  1112.     {
  1113.         if(!$this->getCacheNeed())
  1114.             return;
  1115.        
  1116.         if($this->currentCache == 'null')
  1117.             throw new Main\SystemException('Cache were not started');
  1118.        
  1119.         $this->currentCache->abortDataCache();
  1120.         $this->currentCache = null;
  1121.     }
  1122.    
  1123.     /**
  1124.      * Function return data stored in cache
  1125.      * @throws Main\SystemException
  1126.      * @return void|mixed[] Data from cache
  1127.      */
  1128.     final protected function getCacheData()
  1129.     {
  1130.         if(!$this->getCacheNeed())
  1131.             return;
  1132.        
  1133.         if($this->currentCache == 'null')
  1134.             throw new Main\SystemException('Cache were not started');
  1135.        
  1136.         return $this->currentCache->getVars();
  1137.     }
  1138.    
  1139.     /**
  1140.      * Function leaves the ability to modify cache key in future.
  1141.      * @return string Cache key to be used in CPHPCache()
  1142.      */
  1143.     final protected function getCacheKey($cacheId = array())
  1144.     {
  1145.         if(!is_array($cacheId))
  1146.             $cacheId = array((string) $cacheId);
  1147.        
  1148.         $cacheId['SITE_ID'] = SITE_ID;
  1149.         $cacheId['LANGUAGE_ID'] = LANGUAGE_ID;
  1150.         // if there are two or more caches with the same id, but with different cache_time, make them separate
  1151.         $cacheId['CACHE_TIME'] = intval($this->arResult['CACHE_TIME']);
  1152.        
  1153.         if(defined("SITE_TEMPLATE_ID"))
  1154.             $cacheId['SITE_TEMPLATE_ID'] = SITE_TEMPLATE_ID;
  1155.        
  1156.         return implode('|', $cacheId);
  1157.     }
  1158.    
  1159.     public function executeComponent(){
  1160.         global $APPLICATION, $USER;
  1161.         \CAjax::Init();
  1162.         $this->userAuth = $USER->IsAuthorized();
  1163.         $this->templateName = $this->getTemplateName();
  1164.         $this->userID = $USER->GetID();
  1165.         $this->ajax_id = $this->getAjaxID();
  1166.         $this->show_captha = (!$this->userAuth && $this->arParams['USE_CAPTCHA'] == 'Y');
  1167.         $this->arParams["SHOW_CAPTCHA"] = $this->show_captha ? "Y" : "N"; /** Для старых шаблонов */
  1168.         try{
  1169.             $this->checkRequiredModules();
  1170.             $this->processRequest();
  1171.             $this->prepareData();
  1172.             $this->performActions();
  1173.         }catch(Exception $e){
  1174.             $this->errorsFatal[htmlspecialcharsEx($e->getCode())] = htmlspecialcharsEx($e->getMessage());
  1175.         }
  1176.        
  1177.         $this->formatResultErrors();
  1178.        
  1179.        
  1180.        
  1181.         if($this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == $this->ajax_id || $this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == "Y"){
  1182.             $APPLICATION->RestartBuffer();
  1183.         }
  1184.         $this->includeComponentTemplate();
  1185.         if($this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == $this->ajax_id || $this->requestData['AJAX_CALL_BUY_ONE_CLICK'] == "Y"){
  1186.             die();
  1187.         }
  1188.     }
  1189. }
Add Comment
Please, Sign In to add comment