Beispiel #1
0
 public static function setPrice($productID, $priceValue = 0.0, $currency = false, $priceTypeId = false, $priceTypeId = false)
 {
     $productID = intval($productID);
     if ($currency === false) {
         $currency = CCrmCurrency::GetBaseCurrencyID();
     }
     if (strlen($currency) < 3) {
         return false;
     }
     if ($priceTypeId === false) {
         $priceTypeId = self::getSelectedPriceTypeId();
     }
     if (intval($priceTypeId) < 1) {
         return false;
     }
     $ID = false;
     $arFields = false;
     if ($arFields = self::getPrice($productID, $priceTypeId)) {
         $ID = $arFields["ID"];
         $arFields = array("PRICE" => doubleval($priceValue), "CURRENCY" => $currency);
         $ID = CPrice::Update($ID, $arFields);
     } else {
         $arFields = array("PRICE" => doubleval($priceValue), "CURRENCY" => $currency, "QUANTITY_FROM" => 0, "QUANTITY_TO" => 0, "EXTRA_ID" => false, "CATALOG_GROUP_ID" => $priceTypeId, "PRODUCT_ID" => $productID);
         $ID = CPrice::Add($arFields);
     }
     return $ID ? $ID : false;
 }
 private function setExtra($productId, $priceTypeId, $extraId)
 {
     $list = CPrice::GetList(array(), array('PRODUCT_ID' => $productId, 'CATALOG_GROUP_ID' => $priceTypeId), false, false, array('ID', 'EXTRA_ID'));
     $arFields = array('PRODUCT_ID' => $productId, 'CATALOG_GROUP_ID' => $priceTypeId, 'EXTRA_ID' => $extraId, 'CURRENCY' => 'USD');
     if ($res = $list->Fetch()) {
         if ($res['EXTRA_ID'] != $extraId) {
             CPrice::Update($res['ID'], $arFields, true);
         }
     } else {
         CPrice::Add($arFields, true);
     }
     unset($list);
     unset($res);
     unset($resultUp);
 }
Beispiel #3
0
function add_element($iblock_id, $section_id, $NAME, $PRICE_EUR, $P, $DETAIL_PICTURE)
{
    $el = new CIBlockElement();
    //test_dump($P);
    $arFields = array("IBLOCK_ID" => $iblock_id, "NAME" => $NAME, "CODE" => $P["ARTNUMBER"], "ACTIVE" => "Y", "IBLOCK_SECTION_ID" => $section_id, "DETAIL_TEXT" => $P["DESCRIPTION_TEXT"], "DETAIL_TEXT_TYPE" => "html", "PROPERTY_VALUES" => $P, "DETAIL_PICTURE" => $DETAIL_PICTURE);
    if ($last_el_id = $el->Add($arFields)) {
        echo "New ID: " . $last_el_id . "<br>";
        $arFields = array("ID" => $last_el_id, "VAT_INCLUDED" => "Y");
        if (CCatalogProduct::Add($arFields)) {
            echo "Добавили параметры товара к элементу каталога " . $last_el_id . "<br>";
            $arFields = array("PRODUCT_ID" => $last_el_id, "CATALOG_GROUP_ID" => 1, "PRICE" => $PRICE_EUR, "CURRENCY" => "EUR");
            CPrice::Add($arFields);
        } else {
            echo "Ошибка добавления параметров товаров";
        }
    } else {
        echo "Error: " . $el->LAST_ERROR . "<br>";
    }
}
Beispiel #4
0
             }
         } else {
             if (CPrice::Update($arr["ID"], $value)) {
                 $bUpdatePrice = 'Y';
             } else {
                 if ($ex = $APPLICATION->GetException()) {
                     $strPriceErr = GetMessage('CATI_ERR_PRICE_UPDATE') . $ex->GetString();
                 } else {
                     $strPriceErr = GetMessage('CATI_ERR_PRICE_UPDATE_UNKNOWN');
                 }
             }
         }
     } else {
         $boolEmptyNewPrice = isset($value['PRICE']) && '' === $value['PRICE'] && (isset($value['CURRENCY']) && '' === $value['CURRENCY']);
         if (!$boolEmptyNewPrice) {
             if (CPrice::Add($value)) {
                 $bUpdatePrice = 'Y';
             } else {
                 if ($ex = $APPLICATION->GetException()) {
                     $strPriceErr = GetMessage('CATI_ERR_PRICE_ADD') . $ex->GetString();
                 } else {
                     $strPriceErr = GetMessage('CATI_ERR_PRICE_ADD_UNKNOWN');
                 }
             }
         }
     }
     if ('' != $strPriceErr) {
         $strErrorR .= GetMessage("CATI_LINE_NO") . " " . $line_num . ". " . $strPriceErr . '<br>';
         break;
     }
 }
Beispiel #5
0
							elseif(!isset($CATALOG_EXTRA[$elID][$arCatalogGroup["ID"]]))
							{
								$arFields = array(
									"PRODUCT_ID" => $elID,
									"CATALOG_GROUP_ID" => $arCatalogGroup["ID"],
									"PRICE" => $arPrice[$arCatalogGroup["ID"]],
									"CURRENCY" => $arCurrency[$arCatalogGroup["ID"]],
									"QUANTITY_FROM" => $CATALOG_QUANTITY_FROM[$elID][$arCatalogGroup["ID"]],
									"QUANTITY_TO" => $CATALOG_QUANTITY_TO[$elID][$arCatalogGroup["ID"]]
								);
								if($arFields["PRICE"] < 0 || trim($arFields["PRICE"]) === '')
									CPrice::Delete($CATALOG_PRICE_ID[$elID][$arCatalogGroup["ID"]]);
								elseif(intval($CATALOG_PRICE_ID[$elID][$arCatalogGroup["ID"]])>0)
									CPrice::Update(intval($CATALOG_PRICE_ID[$elID][$arCatalogGroup["ID"]]), $arFields);
								elseif($arFields["PRICE"] >= 0)
									CPrice::Add($arFields);
							}
						}
					}
					unset($arCatalogGroup);
				}
			}
		}
	}
}


// Handle actions here
if(($arID = $lAdmin->GroupAction()))
{
	if($_REQUEST['action_target']=='selected')
Beispiel #6
0
 /**
  * @param int $PRODUCT_ID
  * @param array $arPrices
  * @param bool|array $arDiscounts
  */
 function SetProductPrice($PRODUCT_ID, $arPrices, $arDiscounts = false)
 {
     $arDBPrices = array();
     $rsPrice = CPrice::GetList(array(), array("PRODUCT_ID" => $PRODUCT_ID));
     while ($ar = $rsPrice->Fetch()) {
         $arDBPrices[$ar["CATALOG_GROUP_ID"] . ":" . $ar["QUANTITY_FROM"] . ":" . $ar["QUANTITY_TO"]] = $ar["ID"];
     }
     $arToDelete = $arDBPrices;
     if (!is_array($arPrices)) {
         $arPrices = array();
     }
     foreach ($arPrices as $price) {
         if (!isset($price[$this->mess["IBLOCK_XML2_CURRENCY"]])) {
             $price[$this->mess["IBLOCK_XML2_CURRENCY"]] = $price["PRICE"]["CURRENCY"];
         }
         $arPrice = array("PRODUCT_ID" => $PRODUCT_ID, "CATALOG_GROUP_ID" => $price["PRICE"]["ID"], "^PRICE" => $this->ToFloat($price[$this->mess["IBLOCK_XML2_PRICE_FOR_ONE"]]), "CURRENCY" => $this->CheckCurrency($price[$this->mess["IBLOCK_XML2_CURRENCY"]]));
         foreach ($this->ConvertDiscounts($arDiscounts) as $arDiscount) {
             $arPrice["QUANTITY_FROM"] = $arDiscount["QUANTITY_FROM"];
             $arPrice["QUANTITY_TO"] = $arDiscount["QUANTITY_TO"];
             if ($arDiscount["PERCENT"] > 0) {
                 $arPrice["PRICE"] = $arPrice["^PRICE"] - $arPrice["^PRICE"] / 100 * $arDiscount["PERCENT"];
             } else {
                 $arPrice["PRICE"] = $arPrice["^PRICE"];
             }
             $id = $arPrice["CATALOG_GROUP_ID"] . ":" . $arPrice["QUANTITY_FROM"] . ":" . $arPrice["QUANTITY_TO"];
             if (array_key_exists($id, $arDBPrices)) {
                 CPrice::Update($arDBPrices[$id], $arPrice);
                 unset($arToDelete[$id]);
             } else {
                 CPrice::Add($arPrice);
             }
         }
     }
     foreach ($arToDelete as $id) {
         CPrice::Delete($id);
     }
 }
Beispiel #7
0
    /**
     * функция после добавлением элемента в инфоблока
     * @param $arFields поля элемента ифоблока
     * для страницы Объявления
     * eсли VIP объявление то добавляет корзину
     * привязывает по ID созданное объявления к товару в корзине
     * редирект на необходимы url
     */
     function AuthtorizeAfterAds(&$arFields){
         unset($_SESSION['user777999authorize']);
         if($arFields['PROPERTY_VALUES']['114']){
             foreach($arFields['PROPERTY_VALUES']['114'] as $key114 => $item114){
                 if($item114['VALUE']){
                     foreach($arFields['PROPERTY_VALUES']['113'] as $key113 => $item113){
                         if($item113['VALUE']){
                             $arFields['PROPERTY_VALUES']['113'][$key113]=ConvertDateTime($item114['VALUE'], "YYYY-MM-DD HH:MI:SS");
                         }else{
                             $arFields['PROPERTY_VALUES']['113'][n0]=ConvertDateTime($item114['VALUE'], "YYYY-MM-DD HH:MI:SS");
                         }

                     }
                 }
             }
         }

        if(($arFields["IBLOCK_ID"] == 16)&&(!CUser::IsAuthorized())){
            global $USER;
            $rsUser = CUser::GetByID($_SESSION['NEW_USER_ID']);
            $arUser = $rsUser->Fetch();
            $_SESSION['$arUser']=$arUser;
            $USER = new CUser;
            $arAuthResult = $USER->Login($arUser['LOGIN'], $arUser['PASSWORD'], "Y","N");
        }
         //$_SESSION['user777authorize']=$arFields;


         if(($arFields["IBLOCK_ID"] == 16)&&(CModule::IncludeModule("catalog"))&&(CModule::IncludeModule("sale"))){

             $price_product=floatval($arFields["PROPERTY_VALUES"][86]);
             $quantity_product=floatval($arFields["PROPERTY_VALUES"][87]);
             if($price_product){
             $PRODUCT_ID = $arFields['ID'];
             $PRICE_TYPE_ID = 1;

             $arFieldsprice = Array(
                 "PRODUCT_ID" => $PRODUCT_ID,
                 "CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
                 "PRICE" =>$price_product,
                 "CURRENCY" => "RUB",
                 "QUANTITY_FROM" => 1,
             );

             $res = CPrice::GetList(
                 array(),
                 array(
                     "PRODUCT_ID" => $PRODUCT_ID,
                     "CATALOG_GROUP_ID" => $PRICE_TYPE_ID
                 )
             );

             if ($arr = $res->Fetch())
             {
                 CPrice::Update($arr["ID"], $arFieldsprice);
             }
             else
             {
                 CPrice::Add($arFieldsprice,true);
             }
             }

         }

         if (
             (
                 (($arFields["IBLOCK_ID"] == 2)&& (is_numeric($arFields["PROPERTY_VALUES"][73])))
                 ||
                 (($arFields["IBLOCK_ID"] == 15)&& (is_numeric($arFields["PROPERTY_VALUES"][76])))
                 ||
                 (($arFields["IBLOCK_ID"] == 14)&& (is_numeric($arFields["PROPERTY_VALUES"][78])))
             )
             &&
             CModule::IncludeModule("catalog")
             &&
             CModule::IncludeModule("sale")
             &&
             ((strstr($_SERVER['REQUEST_URI'],'/personal/moy-magazin/'))||(strstr($_SERVER['REQUEST_URI'],'/obyavleniya/add-ads/')))
         )
         {


             switch($arFields["IBLOCK_ID"]){
                 case 2:
                     $price_product=floatval($arFields["PROPERTY_VALUES"][73]);
                     $quantity_product=floatval($arFields["PROPERTY_VALUES"][75]);

                     break;
                 case 14:
                     $price_product=floatval($arFields["PROPERTY_VALUES"][78]);
                     $quantity_product=floatval($arFields["PROPERTY_VALUES"][79]);

                     break;
                 case 15:
                     $price_product=floatval($arFields["PROPERTY_VALUES"][76]);
                     $quantity_product=floatval($arFields["PROPERTY_VALUES"][77]);

                     break;
             }
             if($price_product){
                 $PRODUCT_ID = $arFields['ID'];
                 $PRICE_TYPE_ID = 1;
                 if($quantity_product){
                     $ar_res_product=CCatalogProduct::GetByID($PRODUCT_ID);
                     if($ar_res_product['QUANTITY']!=""){
                         $arFields_quant = array(
                             'QUANTITY' => $quantity_product
                         );
                         CCatalogProduct::Update($PRODUCT_ID, $arFields_quant);

                     }else{
                         $arFields_quant = array(
                             'ID'=>$PRODUCT_ID,
                             'QUANTITY' => $quantity_product
                         );
                         CCatalogProduct::Add($arFields_quant);
                     }
                 }
                 $arFieldsprice = Array(
                     "PRODUCT_ID" => $PRODUCT_ID,
                     "CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
                     "PRICE" =>$price_product,
                     "CURRENCY" => "RUB",
                 );

                 $res = CPrice::GetList(
                     array(),
                     array(
                         "PRODUCT_ID" => $PRODUCT_ID,
                         "CATALOG_GROUP_ID" => $PRICE_TYPE_ID
                     )
                 );

                 if ($arr = $res->Fetch())
                 {
                     CPrice::Update($arr["ID"], $arFieldsprice,true);
                     $_SESSION['price_add']=$arr;
                 }
                 else
                 {
                     CPrice::Add($arFieldsprice,true);
                 }
             }

         }


        // добавление в корзину vip и поднять
        if(($arFields["IBLOCK_ID"] == 16)&&(($arFields["PROPERTY_VALUES"][81][0]==40)||($arFields["PROPERTY_VALUES"][81][0]==46))){
            
            unset($_SESSION['ELEMENT_ADS_ID']);
            if(($_REQUEST['CODE'])&&(CModule::IncludeModule("iblock"))){

                if((CModule::IncludeModule("catalog"))&&(CModule::IncludeModule("sale"))){

                    $dbBasketItems = CSaleBasket::GetList(
                        array(),
                        array(
                            "FUSER_ID" => CSaleBasket::GetBasketUserID(),
                            "LID" => SITE_ID,
				            "ORDER_ID" => "NULL"
                        ),
                        false,
                        false,
                        array("ID", "NAME")
                    );
                    if($arFields["PROPERTY_VALUES"][81][0]==46){
                        $test_ads="TEST_ADSUP";
                    }
                    if($arFields["PROPERTY_VALUES"][81][0]==40){
                        $test_ads="TEST_VIP";
                    }
                    while ($arBasketItems = $dbBasketItems->Fetch())
                    {
                        $dbProp = CSaleBasket::GetPropsList(array("SORT" => "ASC", "ID" => "ASC"), array("BASKET_ID" => $arBasketItems["ID"]));
                        if($arProp = $dbProp -> GetNext())
                        {
                            $props[] = $arProp;
                            $dbProp = CSaleBasket::GetPropsList(array("SORT" => "ASC", "ID" => "ASC"), array("BASKET_ID" => $arBasketItems["ID"]));
                            if($arProp = $dbProp -> GetNext())
                            {
                                

                                if($arProp['CODE']==$test_ads){
                                    $ELEMENT_ID = intval($arProp['VALUE']);
                                    if($ELEMENT_ID==$_REQUEST['CODE']){
                                        $vip=true;
                                    }
                                }

                            }
                        }
                    }
                }
            }
            //var_dump($vip);die();
            if(!$vip){
            $arPropsBasket = array();
            if($arFields["PROPERTY_VALUES"][81][0]==46){
                $code_price="up-ads";
                $arPropsBasket[] = array(
                    "NAME" => "Название: ".$arFields['NAME'],
                    "CODE" => "TEST_ADSUP",
                    "VALUE" => $arFields['ID']
                );
            }
            if($arFields["PROPERTY_VALUES"][81][0]==40){
                $code_price="vip-ads";
                $arPropsBasket[] = array(
                    "NAME" => "Название: ".$arFields['NAME'],
                    "CODE" => "TEST_VIP",
                    "VALUE" => $arFields['ID']
                );
            }
            $arSelect2 = Array("ID", "IBLOCK_ID", "NAME","PROPERTY_*");
            $arFilter2 = Array("IBLOCK_ID"=>17, "CODE"=>$code_price, "ACTIVE"=>"Y");
            $res2 = CIBlockElement::GetList(Array(), $arFilter2, false, Array("nPageSize"=>1), $arSelect2);
            while($ob2 = $res2->GetNextElement()){
                $arFieldIdAds = $ob2->GetFields();
                if (CModule::IncludeModule("sale"))
                {

                    $base_price=CPrice::GetBasePrice($arFieldIdAds['ID']);
                    $arFieldsB = array(
                        "PRODUCT_ID" => $arFieldIdAds['ID'],
                        "PRICE" => $base_price['PRICE'],
                        "CURRENCY" => "RUB",
                        "QUANTITY" => 1,
                        "LID" => LANG,
                        "NAME" => $arFieldIdAds['NAME'],
                    );

                    $arFieldsB["PROPS"] = $arPropsBasket;

                    $id_basket = CSaleBasket::Add($arFieldsB);

                    $db_res = CSaleBasket::GetPropsList(
                        array(
                            "SORT" => "ASC",
                            "NAME" => "ASC"
                        ),
                        array("BASKET_ID" => $id_basket)
                    );
                    while ($ar_res = $db_res->Fetch())
                    {
                        $_SESSION['order_fields_after'][]= $ar_res["NAME"]."=".$ar_res["VALUE"]."<br>";
                    }
                }
            }




            }


            unset($_SESSION['NEW_USER_ID']);
            LocalRedirect('/personal/cart/');

        }

         if(($arFields["IBLOCK_ID"] == 16)&&($arFields["PROPERTY_VALUES"][81][0]==47)){
             $_SESSION['ELEMENT_ADS_ID']=$arFields['ID'];

         }



         }
             if ($arCatalogPrice_tmp[$i]["ID"] > 0) {
                 $arCatalogPrice = CPrice::GetByID($arCatalogPrice_tmp[$i]["ID"]);
                 if ($arCatalogPrice && $arCatalogPrice["PRODUCT_ID"] == $PRODUCT_ID) {
                     $arUpdatedIDs[] = $arCatalogPrice_tmp[$i]["ID"];
                     if (!CPrice::Update($arCatalogPrice_tmp[$i]["ID"], $arCatalogFields)) {
                         $strWarning .= str_replace("#ID#", $arCatalogPrice_tmp[$i]["ID"], GetMessage("C2IT_ERROR_PRPARAMS")) . "<br>";
                     }
                 } else {
                     $ID_tmp = CPrice::Add($arCatalogFields);
                     $arUpdatedIDs[] = $ID_tmp;
                     if (!$ID_tmp) {
                         $strWarning .= str_replace("#PRICE#", $arCatalogFields["PRICE"], GetMessage("C2IT_ERROR_SAVEPRICE")) . "<br>";
                     }
                 }
             } else {
                 $ID_tmp = CPrice::Add($arCatalogFields);
                 $arUpdatedIDs[] = $ID_tmp;
                 if (!$ID_tmp) {
                     $strWarning .= str_replace("#PRICE#", $arCatalogFields["PRICE"], GetMessage("C2IT_ERROR_SAVEPRICE")) . "<br>";
                 }
             }
         }
     }
 }
 CPrice::DeleteByProduct($PRODUCT_ID, $arUpdatedIDs);
 \Bitrix\Iblock\PropertyIndex\Manager::updateElementIndex($IBLOCK_ID, $PRODUCT_ID);
 if ($arCatalog["SUBSCRIPTION"] == "Y") {
     $arCurProductGroups = array();
     $dbProductGroups = CCatalogProductGroups::GetList(array(), array("PRODUCT_ID" => $ID), false, false, array("ID", "GROUP_ID", "ACCESS_LENGTH", "ACCESS_LENGTH_TYPE"));
     while ($arProductGroup = $dbProductGroups->Fetch()) {
         $arCurProductGroups[IntVal($arProductGroup["GROUP_ID"])] = $arProductGroup;
 /**
  *
  * History update, cron usage only
  * @global CUser $USER
  * @return boolean
  */
 public static function orderHistory()
 {
     global $USER;
     if (is_object($USER) == false) {
         $USER = new RetailUser();
     }
     if (!CModule::IncludeModule("iblock")) {
         self::eventLog('ICrmOrderActions::orderHistory', 'iblock', 'module not found');
         return false;
     }
     if (!CModule::IncludeModule("sale")) {
         self::eventLog('ICrmOrderActions::orderHistory', 'sale', 'module not found');
         return false;
     }
     if (!CModule::IncludeModule("catalog")) {
         self::eventLog('ICrmOrderActions::orderHistory', 'catalog', 'module not found');
         return false;
     }
     $api_host = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_HOST_OPTION, 0);
     $api_key = COption::GetOptionString(self::$MODULE_ID, self::$CRM_API_KEY_OPTION, 0);
     $optionsOrderTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_TYPES_ARR, 0)));
     $optionsDelivTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_DELIVERY_TYPES_ARR, 0)));
     $optionsPayTypes = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_TYPES, 0)));
     $optionsPayStatuses = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT_STATUSES, 0)));
     // --statuses
     $optionsPayment = array_flip(unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_PAYMENT, 0)));
     $optionsOrderProps = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_PROPS, 0));
     $optionsLegalDetails = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_LEGAL_DETAILS, 0));
     $optionsContragentType = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CONTRAGENT_TYPE, 0));
     $optionsSitesList = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_SITES_LIST, 0));
     $optionsCustomFields = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CUSTOM_FIELDS, 0));
     foreach ($optionsOrderProps as $code => $value) {
         if (isset($optionsLegalDetails[$code])) {
             $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsLegalDetails[$code]);
         }
         if (isset($optionsCustomFields[$code])) {
             $optionsOrderProps[$code] = array_merge($optionsOrderProps[$code], $optionsCustomFields[$code]);
         }
         $optionsOrderProps[$code]['location'] = 'LOCATION';
         if (array_search('CITY', $optionsOrderProps[$code]) == false) {
             $optionsOrderProps[$code]['city'] = 'CITY';
         }
         if (array_search('ZIP', $optionsOrderProps[$code]) == false) {
             $optionsOrderProps[$code]['index'] = 'ZIP';
         }
     }
     $api = new RetailCrm\RestApi($api_host, $api_key);
     $dateStart = COption::GetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, null);
     if (is_null($dateStart)) {
         $dateStart = new \DateTime();
         $dateStart = $dateStart->format('Y-m-d H:i:s');
     }
     try {
         $orderHistory = $api->orderHistory($dateStart);
     } catch (\RetailCrm\Exception\CurlException $e) {
         self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::orderHistory::CurlException', $e->getCode() . ': ' . $e->getMessage());
         return false;
     }
     $orderHistory = isset($orderHistory['orders']) ? $orderHistory['orders'] : array();
     $log = new Logger();
     $log->write($orderHistory, 'history');
     $dateFinish = $api->getGeneratedAt();
     if (is_null($dateFinish) || $dateFinish == false) {
         $dateFinish = new \DateTime();
     }
     $defaultOrderType = 1;
     $dbOrderTypesList = CSalePersonType::GetList(array(), array("ACTIVE" => "Y"));
     if ($arOrderTypesList = $dbOrderTypesList->Fetch()) {
         $defaultOrderType = $arOrderTypesList['ID'];
     }
     $GLOBALS['INTARO_CRM_FROM_HISTORY'] = true;
     foreach ($orderHistory as $order) {
         if (function_exists('intarocrm_order_pre_persist')) {
             $order = intarocrm_order_pre_persist($order);
         }
         if (!isset($order['externalId'])) {
             // custom orderType function
             if (function_exists('intarocrm_set_order_type')) {
                 $orderType = intarocrm_set_order_type($order);
                 if ($orderType) {
                     $optionsOrderTypes[$order['orderType']] = $orderType;
                 } else {
                     $optionsOrderTypes[$order['orderType']] = $defaultOrderType;
                 }
             }
             // we dont need new orders without any customers (can check only for externalId)
             if (!isset($order['customer']['externalId'])) {
                 if (!isset($order['customer']['id'])) {
                     continue;
                 }
                 $registerNewUser = true;
                 if (!isset($order['customer']['email']) || $order['customer']['email'] == '') {
                     $login = $order['customer']['email'] = uniqid('user_' . time()) . '@crm.com';
                 } else {
                     $dbUser = CUser::GetList($by = 'ID', $sort = 'ASC', array('=EMAIL' => $order['email']));
                     switch ($dbUser->SelectedRowsCount()) {
                         case 0:
                             $login = $order['customer']['email'];
                             break;
                         case 1:
                             $arUser = $dbUser->Fetch();
                             $registeredUserID = $arUser['ID'];
                             $registerNewUser = false;
                             break;
                         default:
                             $login = uniqid('user_' . time()) . '@crm.com';
                             break;
                     }
                 }
                 if ($registerNewUser === true) {
                     $userPassword = uniqid();
                     $newUser = new CUser();
                     $arFields = array("NAME" => self::fromJSON($order['customer']['firstName']), "LAST_NAME" => self::fromJSON($order['customer']['lastName']), "EMAIL" => $order['customer']['email'], "LOGIN" => $login, "LID" => "ru", "ACTIVE" => "Y", "PASSWORD" => $userPassword, "CONFIRM_PASSWORD" => $userPassword);
                     $registeredUserID = $newUser->Add($arFields);
                     if ($registeredUserID === false) {
                         self::eventLog('ICrmOrderActions::orderHistory', 'CUser::Register', 'Error register user');
                         continue;
                     }
                     try {
                         $api->customerFixExternalIds(array(array('id' => $order['customer']['id'], 'externalId' => $registeredUserID)));
                     } catch (\RetailCrm\Exception\CurlException $e) {
                         self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::customerFixExternalIds::CurlException', $e->getCode() . ': ' . $e->getMessage());
                         continue;
                     }
                 }
                 $order['customer']['externalId'] = $registeredUserID;
             }
             // new order
             $newOrderFields = array('LID' => CSite::GetDefSite(), 'PERSON_TYPE_ID' => isset($optionsOrderTypes[$order['orderType']]) ? $optionsOrderTypes[$order['orderType']] : $defaultOrderType, 'PAYED' => 'N', 'CANCELED' => 'N', 'STATUS_ID' => 'N', 'PRICE' => 0, 'CURRENCY' => CCurrency::GetBaseCurrency(), 'USER_ID' => $order['customer']['externalId'], 'PAY_SYSTEM_ID' => 0, 'PRICE_DELIVERY' => 0, 'DELIVERY_ID' => 0, 'DISCOUNT_VALUE' => 0, 'USER_DESCRIPTION' => '');
             if (count($optionsSitesList) > 1 && ($lid = array_search($order['site'], $optionsSitesList))) {
                 $newOrderFields['LID'] = $lid;
             }
             $externalId = CSaleOrder::Add($newOrderFields);
             if (!isset($order['externalId'])) {
                 try {
                     $api->orderFixExternalIds(array(array('id' => $order['id'], 'externalId' => $externalId)));
                 } catch (\RetailCrm\Exception\CurlException $e) {
                     self::eventLog('ICrmOrderActions::orderHistory', 'RetailCrm\\RestApi::orderFixExternalIds::CurlException', $e->getCode() . ': ' . $e->getMessage());
                     continue;
                 }
             }
             $order['externalId'] = $externalId;
         }
         if (isset($order['externalId']) && $order['externalId']) {
             // custom orderType function
             if (function_exists('intarocrm_set_order_type')) {
                 $orderType = intarocrm_set_order_type($order);
                 if ($orderType) {
                     $optionsOrderTypes[$order['orderType']] = $orderType;
                 } else {
                     $optionsOrderTypes[$order['orderType']] = $defaultOrderType;
                 }
             }
             $arFields = CSaleOrder::GetById($order['externalId']);
             // incorrect order
             if ($arFields === false || empty($arFields)) {
                 continue;
             }
             $LID = $arFields['LID'];
             $userId = $arFields['USER_ID'];
             if (isset($order['customer']['externalId']) && !is_null($order['customer']['externalId'])) {
                 $userId = $order['customer']['externalId'];
             }
             $rsOrderProps = CSaleOrderPropsValue::GetList(array(), array('ORDER_ID' => $arFields['ID']));
             $arUpdateProps = array();
             while ($ar = $rsOrderProps->Fetch()) {
                 $prop = CSaleOrderProps::GetByID($ar['ORDER_PROPS_ID']);
                 $arUpdateProps[$ar['CODE']] = array('ID' => $ar['ID'], 'TYPE' => $prop['TYPE'], 'VALUE' => $ar['VALUE']);
             }
             $order['fio'] = trim(implode(' ', array(isset($order['lastName']) ? $order['lastName'] : '', isset($order['firstName']) ? $order['firstName'] : '', isset($order['patronymic']) ? $order['patronymic'] : '')));
             if (isset($order['delivery']['address']['city'])) {
                 $order['location'] = $order['delivery']['address']['city'];
             }
             if (isset($order['orderType']) && isset($optionsOrderTypes[$order['orderType']])) {
                 if (isset($optionsOrderProps[$arFields['PERSON_TYPE_ID']])) {
                     foreach ($optionsOrderProps[$arFields['PERSON_TYPE_ID']] as $code => $value) {
                         if (in_array($code, array_keys($order)) === false && isset($optionsOrderProps[$optionsOrderTypes[$order['orderType']]][$code])) {
                             $order[$code] = $arUpdateProps[$optionsOrderProps[$arFields['PERSON_TYPE_ID']][$code]]['VALUE'];
                         }
                     }
                 }
                 //update ordertype
                 CSaleOrder::Update($order['externalId'], array('PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']]));
                 $arProp = CSaleOrderProps::GetList(array(), array('PERSON_TYPE_ID' => $optionsOrderTypes[$order['orderType']]));
                 $typeParam = array();
                 while ($ar = $arProp->Fetch()) {
                     $typeParam[$ar['CODE']] = $ar['CODE'];
                 }
                 foreach (array_diff_key($arUpdateProps, $typeParam) as $code => $param) {
                     if (isset($arUpdateProps[$code])) {
                         CSaleOrderPropsValue::Delete($param['ID']);
                     }
                 }
                 $arFields['PERSON_TYPE_ID'] = $optionsOrderTypes[$order['orderType']];
             }
             array_walk_recursive(self::clearArr($order), 'self::recursiveUpdate', array('update' => $arUpdateProps, 'type' => $arFields['PERSON_TYPE_ID'], 'options' => $optionsOrderProps, 'orderId' => $order['externalId']));
             foreach ($order['items'] as $item) {
                 if (isset($item['deleted']) && $item['deleted']) {
                     if ($p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['id']))->Fetch()) {
                         if (!CSaleBasket::Delete($p['ID'])) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error element delete');
                         }
                     } else {
                         $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['id']))->Fetch();
                         if (!CSaleBasket::Delete($prp['BASKET_ID'])) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Delete', 'Error castom element delete');
                         }
                     }
                     continue;
                 }
                 if (isset($item['offer']) === false && isset($item['offer']['externalId']) === false) {
                     continue;
                 }
                 $res = CIBlockElement::GetByID($item['offer']['externalId'])->Fetch();
                 if ($res) {
                     $p = CSaleBasket::GetList(array(), array('ORDER_ID' => $order['externalId'], 'PRODUCT_ID' => $item['offer']['externalId']))->Fetch();
                     if ($p == false) {
                         $p = CIBlockElement::GetByID($item['offer']['externalId'])->GetNext();
                         $iblock = CIBlock::GetByID($p['IBLOCK_ID'])->Fetch();
                         $p['CATALOG_XML_ID'] = $iblock['XML_ID'];
                         $p['PRODUCT_XML_ID'] = $p['XML_ID'];
                         unset($p['XML_ID']);
                     } elseif ($propResult = CSaleBasket::GetPropsList(array(''), array('BASKET_ID' => $p['ID']))) {
                         while ($r = $propResult->Fetch()) {
                             unset($r['ID']);
                             unset($r['BASKET_ID']);
                             $p['PROPS'][] = $r;
                         }
                     }
                     $arProduct = array();
                     if (isset($item['created']) && $item['created'] == true) {
                         $productPrice = GetCatalogProductPrice($item['offer']['externalId'], COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0));
                         $arProduct = array('FUSER_ID' => $userId, 'ORDER_ID' => $order['externalId'], 'QUANTITY' => $item['quantity'], 'CURRENCY' => $productPrice['CURRENCY'], 'LID' => $LID, 'PRODUCT_ID' => $item['offer']['externalId'], 'PRODUCT_PRICE_ID' => $p['PRODUCT_PRICE_ID'], 'WEIGHT' => $p['WEIGHT'], 'DELAY' => $p['DELAY'], 'CAN_BUY' => $p['CAN_BUY'], 'MODULE' => $p['MODULE'], 'NOTES' => $item['comment'] ?: $p['NOTES'], 'PRODUCT_PROVIDER_CLASS' => $p['PRODUCT_PROVIDER_CLASS'], 'DETAIL_PAGE_URL' => $p['DETAIL_PAGE_URL'], 'CATALOG_XML_ID' => $p['CATALOG_XML_ID'], 'PRODUCT_XML_ID' => $p['PRODUCT_XML_ID'], 'CUSTOM_PRICE' => 'Y');
                     }
                     if (isset($item['isCanceled']) == false) {
                         if (isset($item['initialPrice']) && $item['initialPrice']) {
                             $arProduct['PRICE'] = (double) $item['initialPrice'];
                         }
                         if (isset($item['discount'])) {
                             $arProduct['DISCOUNT_PRICE'] = $item['discount'];
                         }
                         if (isset($item['discountPercent'])) {
                             $arProduct['DISCOUNT_VALUE'] = $item['discountPercent'];
                             $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2);
                             $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice;
                         }
                         if (isset($item['discount']) || isset($item['discountPercent'])) {
                             $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE'];
                         }
                         if (isset($item['offer']['name']) && $item['offer']['name']) {
                             $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                         }
                         $arProduct = self::updateCancelProp($arProduct, 0);
                     } elseif (isset($item['isCanceled'])) {
                         $arProduct['PRICE'] = 0;
                         $arProduct = self::updateCancelProp($arProduct, 1);
                     }
                     if (isset($item['created']) && $item['created'] == true) {
                         if (!Add2BasketByProductID($item['offer']['externalId'], $item['quantity'], $arProduct, $p['PROPS'])) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error element add');
                         }
                         continue;
                     }
                     if (count($p['PROPS']) > 0) {
                         $arProduct['PROPS'] = $p['PROPS'];
                     }
                     if (isset($item['quantity']) && $item['quantity']) {
                         $arProduct['QUANTITY'] = $item['quantity'];
                     }
                     if (isset($item['offer']['name']) && $item['offer']['name']) {
                         $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                     }
                     if (!CSaleBasket::Update($p['ID'], $arProduct)) {
                         self::eventLog('ICrmOrderActions::orderHistory', 'CSaleBasket::Update', 'Error element update');
                     }
                     CSaleBasket::DeleteAll($userId);
                 } else {
                     $arProduct = array();
                     if (isset($item['created']) && $item['created'] == true) {
                         $arProduct = array('FUSER_ID' => $userId, 'ORDER_ID' => $order['externalId'], 'LID' => $LID, 'NOTES' => $item['comment']);
                     }
                     if (isset($item['isCanceled']) == false) {
                         if (isset($item['initialPrice']) && $item['initialPrice']) {
                             $arProduct['PRICE'] = (double) $item['initialPrice'];
                         }
                         if (isset($item['discount'])) {
                             $arProduct['DISCOUNT_PRICE'] = $item['discount'];
                         }
                         if (isset($item['discountPercent'])) {
                             $arProduct['DISCOUNT_VALUE'] = $item['discountPercent'];
                             $newPrice = round($arProduct['PRICE'] / 100 * (100 - $arProduct['DISCOUNT_VALUE']), 2);
                             $arProduct['DISCOUNT_PRICE'] = $arProduct['DISCOUNT_PRICE'] + $arProduct['PRICE'] - $newPrice;
                         }
                         if (isset($item['discount']) || isset($item['discountPercent'])) {
                             $arProduct['PRICE'] -= $arProduct['DISCOUNT_PRICE'];
                         }
                         if (isset($item['offer']['name']) && $item['offer']['name']) {
                             $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                         }
                         $arProduct = self::updateCancelProp($arProduct, 0);
                     } elseif (isset($item['isCanceled'])) {
                         $arProduct['PRICE'] = 0;
                         $arProduct = self::updateCancelProp($arProduct, 1);
                     }
                     if (isset($item['quantity']) && $item['quantity']) {
                         $arProduct['QUANTITY'] = $item['quantity'];
                     }
                     if (isset($item['offer']['name']) && $item['offer']['name']) {
                         $arProduct['NAME'] = self::fromJSON($item['offer']['name']);
                     }
                     if (isset($item['created']) && $item['created'] == true) {
                         $iBlocks = unserialize(COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_IBLOCKS, 0));
                         $iBlock = array_shift($iBlocks);
                         $newSection = new CIBlockSection();
                         $newSectionFields = array("ACTIVE" => 'N', "IBLOCK_ID" => $iBlock, "NAME" => 'RetailCRM', "CODE" => 'RetailCRM');
                         $resSection = $newSection->Add($newSectionFields);
                         if (!$resSection) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Add', 'Error castom section add');
                             continue;
                         }
                         $arLoadProductArray = array("IBLOCK_SECTION_ID" => $resSection, "IBLOCK_ID" => $iBlock, "NAME" => $item['offer']['name'] ? $item['offer']['name'] : 'RetailCrmElement', "CODE" => 'RetailCrmElement', "ACTIVE" => 'Y');
                         $el = new CIBlockElement();
                         $PRODUCT_ID = $el->Add($arLoadProductArray, false, false, true);
                         if (!$PRODUCT_ID) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockElement::Add', 'Error castom element add');
                             continue;
                         }
                         if (!CCatalogProduct::Add(array("ID" => $PRODUCT_ID))) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CCatalogProduct::Add', 'Error product add');
                             continue;
                         }
                         $arFields = array("PRODUCT_ID" => $PRODUCT_ID, "CATALOG_GROUP_ID" => COption::GetOptionString(self::$MODULE_ID, self::$CRM_CATALOG_BASE_PRICE, 0), "PRICE" => $item['initialPrice'] ? $item['initialPrice'] : 1, "CURRENCY" => CCurrency::GetBaseCurrency());
                         if (!CPrice::Add($arFields)) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CPrice::Add', 'Error price add');
                             continue;
                         }
                         $Params = array(array('NAME' => 'id', 'CODE' => 'ID', 'VALUE' => $item['offer']['externalId']));
                         if (!Add2BasketByProductID($PRODUCT_ID, $item['quantity'], $arProduct, $Params)) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'Add2BasketByProductID', 'Error add to basket');
                             continue;
                         }
                         if (!CIBlockSection::Delete($resSection)) {
                             self::eventLog('ICrmOrderActions::orderHistory', 'CIBlockSection::Delete', 'Error delete section');
                             continue;
                         }
                         continue;
                     }
                     $prp = CSaleBasket::GetPropsList(array(), array("ORDER_ID" => $order['externalId'], "CODE" => 'ID', "VALUE" => $item['offer']['externalId']))->Fetch();
                     CSaleBasket::Update($prp['BASKET_ID'], $arProduct);
                 }
             }
             if (isset($order['delivery']) === false || isset($order['delivery']['cost']) === false) {
                 $order['delivery']['cost'] = $arFields['PRICE_DELIVERY'];
             }
             if (isset($order['summ']) === false || $order['summ'] <= 0) {
                 $order['summ'] = $arFields['PRICE'] - $arFields['PRICE_DELIVERY'];
             }
             $wasCanaceled = $arFields['CANCELED'] == 'Y' ? true : false;
             if (isset($optionsDelivTypes[$order['delivery']['code']])) {
                 $resultDeliveryTypeId = $optionsDelivTypes[$order['delivery']['code']];
             } else {
                 $resultDeliveryTypeId = isset($order['delivery']['service']) && isset($order['delivery']['service']['code']) ? reset(explode(":", $arFields['DELIVERY_ID'], 1)) : $arFields['DELIVERY_ID'];
             }
             if (isset($order['delivery']['service']) && isset($order['delivery']['service']['code'])) {
                 $deliveryHandler = reset(CSaleDeliveryHandler::GetBySID($resultDeliveryTypeId)->arResult);
                 if (count($deliveryHandler) > 0 && array_key_exists($order['delivery']['service']['code'], $deliveryHandler['PROFILES'])) {
                     $resultDeliveryTypeId = $resultDeliveryTypeId . ':' . $order['delivery']['service']['code'];
                 }
             }
             // orderUpdate
             $arFields = self::clearArr(array('PRICE_DELIVERY' => $order['delivery']['cost'], 'PRICE' => $order['summ'] + (double) $order['delivery']['cost'], 'DATE_MARKED' => $order['markDatetime'], 'USER_ID' => $userId, 'PAY_SYSTEM_ID' => $optionsPayTypes[$order['paymentType']], 'DELIVERY_ID' => $resultDeliveryTypeId, 'STATUS_ID' => $optionsPayStatuses[$order['status']], 'REASON_CANCELED' => self::fromJSON($order['statusComment']), 'USER_DESCRIPTION' => self::fromJSON($order['customerComment']), 'COMMENTS' => self::fromJSON($order['managerComment'])));
             if (isset($order['discount'])) {
                 $arFields['DISCOUNT_VALUE'] = $order['discount'];
                 $arFields['PRICE'] -= $order['discount'];
             }
             if (!empty($arFields)) {
                 CSaleOrder::Update($order['externalId'], $arFields);
             }
             if (isset($order['status']) && $order['status']) {
                 if (isset($optionsPayStatuses[$order['status']]) && $optionsPayStatuses[$order['status']]) {
                     // set STATUS_ID
                     CSaleOrder::StatusOrder($order['externalId'], $optionsPayStatuses[$order['status']]);
                     if ($wasCanaceled && $optionsPayStatuses[$order['status']] != 'YY') {
                         CSaleOrder::CancelOrder($order['externalId'], "N", $order['statusComment']);
                     } elseif ($optionsPayStatuses[$order['status']] == 'YY') {
                         CSaleOrder::CancelOrder($order['externalId'], "Y", $order['statusComment']);
                     }
                 }
             }
             // set PAYED
             if (isset($order['paymentStatus']) && $order['paymentStatus'] && $optionsPayment[$order['paymentStatus']]) {
                 CSaleOrder::PayOrder($order['externalId'], $optionsPayment[$order['paymentStatus']]);
             }
             if (function_exists('intarocrm_order_post_persist')) {
                 intarocrm_order_post_persist($order);
             }
         }
     }
     if (count($orderHistory) > 0) {
         COption::SetOptionString(self::$MODULE_ID, self::$CRM_ORDER_HISTORY_DATE, $dateFinish->format('Y-m-d H:i:s'));
     }
     $GLOBALS['INTARO_CRM_FROM_HISTORY'] = false;
     return true;
 }
Beispiel #10
0
    public static function OnBeforePrologHandler()
    {
        global $USER_FIELD_MANAGER;
        if (isset($_REQUEST['action_button']) && !isset($_REQUEST['action'])) {
            $_REQUEST['action'] = $_REQUEST['action_button'];
        }
        if (!isset($_REQUEST['action'])) {
            return;
        }
        $BID = isset($_REQUEST['ID']) ? (int) $_REQUEST['ID'] : 0;
        if ($_REQUEST['action'] == 'asd_prop_export' && $BID > 0 && check_bitrix_sessid() && CModule::IncludeModule('iblock') && CASDIblockRights::IsIBlockEdit($BID)) {
            $strPath = $_SERVER['DOCUMENT_ROOT'] . '/bitrix/tmp/asd.iblock/';
            $strName = 'asd_props_export_' . $BID . '_' . md5(LICENSE_KEY) . '.xml';
            CheckDirPath($strPath);
            if ($hdlOutput = fopen($strPath . $strName, 'wb')) {
                fwrite($hdlOutput, '<?xml version="1.0" encoding="' . SITE_CHARSET . '"?>' . "\n");
                fwrite($hdlOutput, '<asd_iblock_props>' . "\n");
                fwrite($hdlOutput, CASDiblockTools::ExportPropsToXML($BID, $_REQUEST['p']));
                if ($_REQUEST['forms'] == 'Y') {
                    fwrite($hdlOutput, CASDiblockTools::ExportSettingsToXML($BID, array('forms')));
                }
                fwrite($hdlOutput, '</asd_iblock_props>' . "\n");
                fclose($hdlOutput);
            }
            ?>
<script type="text/javascript">
				top.BX.closeWait(); top.BX.WindowManager.Get().AllowClose(); top.BX.WindowManager.Get().Close();
				window.location.href = '/bitrix/tools/asd.iblock/props_export.php?ID=<?php 
            echo $BID;
            ?>
';
			</script><?php 
            die;
        }
        if ($_REQUEST['action'] == 'asd_prop_import' && $BID > 0 && !$_FILES['xml_file']['error'] && check_bitrix_sessid() && CModule::IncludeModule('iblock') && CASDIblockRights::IsIBlockEdit($BID)) {
            CASDiblockTools::ImportPropsFromXML($BID, $_FILES['xml_file']['tmp_name'], $arOldNewID);
            CASDiblockTools::ImportFormsFromXML($BID, $_FILES['xml_file']['tmp_name'], $arOldNewID);
            LocalRedirect('/bitrix/admin/iblock_edit.php?type=' . $_REQUEST['type'] . '&tabControl_active_tab=edit2&lang=' . LANGUAGE_ID . '&ID=' . $BID . '&admin=Y');
        }
        $IBLOCK_ID = 0;
        if (isset($_REQUEST['IBLOCK_ID'])) {
            $IBLOCK_ID = (int) $_REQUEST['IBLOCK_ID'];
            if ($IBLOCK_ID < 0) {
                $IBLOCK_ID = 0;
            }
        }
        if ($_REQUEST['action'] == 'asd_reverse' && $IBLOCK_ID > 0 && check_bitrix_sessid() && CModule::IncludeModule('iblock') && CASDIblockRights::IsIBlockEdit($IBLOCK_ID)) {
            $LIST_MODE = CIBlock::GetArrayByID($IBLOCK_ID, 'LIST_MODE');
            if (!strlen($LIST_MODE)) {
                $LIST_MODE = COption::GetOptionString('iblock', 'combined_list_mode', 'N') == 'Y' ? 'C' : 'S';
            }
            $LIST_MODE = $LIST_MODE == 'C' ? 'S' : 'C';
            $ib = new CIBlock();
            $ib->Update($IBLOCK_ID, array('LIST_MODE' => $LIST_MODE));
            LocalRedirect('/bitrix/admin/' . ($LIST_MODE == 'S' ? 'iblock_element_admin' : 'iblock_list_admin') . '.php?IBLOCK_ID=' . $IBLOCK_ID . '&type=' . htmlspecialcharsbx($_REQUEST['type']) . '&find_section_section=' . intval($_REQUEST['find_section_section']) . '&lang=' . LANGUAGE_ID);
        }
        $strCurPage = $GLOBALS['APPLICATION']->GetCurPage();
        $bElemPage = $strCurPage == '/bitrix/admin/iblock_element_admin.php' || $strCurPage == '/bitrix/admin/cat_product_admin.php';
        $bSectPage = $strCurPage == '/bitrix/admin/iblock_section_admin.php' || $strCurPage == '/bitrix/admin/cat_section_admin.php';
        $bMixPage = $strCurPage == '/bitrix/admin/iblock_list_admin.php';
        $bRightPage = $bElemPage || $bSectPage || $bMixPage;
        $successRedirect = false;
        if ($bRightPage && $_REQUEST['action'] == 'asd_copy_in_list' && strlen($_REQUEST['ID']) > 0) {
            $bDoAction = true;
            $_REQUEST['action'] = 'asd_copy';
            $_REQUEST['asd_ib_dest'] = $IBLOCK_ID;
            $_REQUEST['ID'] = array($_REQUEST['ID']);
        } else {
            $bDoAction = false;
        }
        if ($bRightPage && check_bitrix_sessid() && !empty($_REQUEST['ID']) && ($_SERVER['REQUEST_METHOD'] == 'POST' || $bDoAction) && CModule::IncludeModule('iblock') && ($_REQUEST['action'] == 'asd_copy' || $_REQUEST['action'] == 'asd_move') && isset($_REQUEST['asd_ib_dest']) && (int) $_REQUEST['asd_ib_dest'] > 0 && CASDIblockRights::IsIBlockDisplay($_REQUEST['asd_ib_dest'])) {
            $intSrcIBlockID = $IBLOCK_ID;
            $intDestIBlockID = (int) $_REQUEST['asd_ib_dest'];
            $intSetSectID = 0;
            if (isset($_REQUEST['asd_sect_dest'])) {
                $intSetSectID = (int) $_REQUEST['asd_sect_dest'];
                if ($intSetSectID < 0) {
                    $intSetSectID = 0;
                }
            }
            $boolCreateElement = false;
            $boolCreateSection = false;
            if ($bElemPage || $bMixPage) {
                $boolCreateElement = CASDIblockRights::IsSectionElementCreate($intDestIBlockID, $intSetSectID);
            }
            if ($bSectPage || $bMixPage) {
                $boolCreateSection = CASDIblockRights::IsSectionSectionCreate($intDestIBlockID, $intSetSectID);
            }
            if ($boolCreateElement || $boolCreateSection) {
                $arPropListCache = array();
                $arOldPropListCache = array();
                $arNamePropListCache = array();
                $arOldNamePropListCache = array();
                $boolUFListCache = false;
                $arUFListCache = array();
                $arOldUFListCache = array();
                $arUFEnumCache = array();
                $arOldUFEnumCache = array();
                $arUFNameEnumCache = array();
                $arOldUFNameEnumCache = array();
                $arDestIBlock = CIBlock::GetArrayByID($intDestIBlockID);
                $arDestIBFields = $arDestIBlock['FIELDS'];
                $boolCodeUnique = false;
                if ($arDestIBFields['CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                    $boolCodeUnique = $intSrcIBlockID == $intDestIBlockID;
                }
                $boolSectCodeUnique = false;
                if ($arDestIBFields['SECTION_CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                    $boolSectCodeUnique = $intSrcIBlockID == $intDestIBlockID;
                }
                $boolCatalog = CModule::IncludeModule('catalog');
                $boolCopyCatalog = false;
                $boolNewCatalog = false;
                if ($boolCatalog) {
                    $boolCopyCatalog = is_array(CCatalog::GetByID($intDestIBlockID));
                    $boolNewCatalog = $boolCopyCatalog;
                    if ($boolCopyCatalog) {
                        $boolCopyCatalog = is_array(CCatalog::GetByID($intSrcIBlockID));
                    }
                }
                $el = new CIBlockElement();
                $sc = new CIBlockSection();
                $obEnum = new CUserFieldEnum();
                foreach ($_REQUEST['ID'] as $eID) {
                    $boolCopyElem = false;
                    $boolCopySect = false;
                    if ($bMixPage) {
                        if (substr($eID, 0, 1) != 'E') {
                            $boolCopySect = true;
                        } else {
                            $boolCopyElem = true;
                        }
                        $ID = (int) substr($eID, 1);
                    } else {
                        $boolCopyElem = $bElemPage;
                        $boolCopySect = $bSectPage;
                        $ID = (int) $eID;
                    }
                    if ($boolCreateElement && $boolCopyElem) {
                        if ($obSrc = CIBlockElement::GetByID($ID)->GetNextElement()) {
                            $arSrc = $obSrc->GetFields();
                            $arSrcPr = $obSrc->GetProperties(false, array('EMPTY' => 'N'));
                            $arSrc['PREVIEW_PICTURE'] = (int) $arSrc['PREVIEW_PICTURE'];
                            if ($arSrc['PREVIEW_PICTURE'] > 0) {
                                $arSrc['PREVIEW_PICTURE'] = CFile::MakeFileArray($arSrc['PREVIEW_PICTURE']);
                                if (empty($arSrc['PREVIEW_PICTURE'])) {
                                    $arSrc['PREVIEW_PICTURE'] = false;
                                } else {
                                    $arSrc['PREVIEW_PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arSrc['PREVIEW_PICTURE'] = false;
                            }
                            $arSrc['DETAIL_PICTURE'] = (int) $arSrc['DETAIL_PICTURE'];
                            if ($arSrc['DETAIL_PICTURE'] > 0) {
                                $arSrc['DETAIL_PICTURE'] = CFile::MakeFileArray($arSrc['DETAIL_PICTURE']);
                                if (empty($arSrc['DETAIL_PICTURE'])) {
                                    $arSrc['DETAIL_PICTURE'] = false;
                                } else {
                                    $arSrc['DETAIL_PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arSrc['DETAIL_PICTURE'] = false;
                            }
                            $arSrc = array('IBLOCK_ID' => $intDestIBlockID, 'ACTIVE' => $arSrc['ACTIVE'], 'ACTIVE_FROM' => $arSrc['ACTIVE_FROM'], 'ACTIVE_TO' => $arSrc['ACTIVE_TO'], 'SORT' => $arSrc['SORT'], 'NAME' => $arSrc['~NAME'], 'PREVIEW_PICTURE' => $arSrc['PREVIEW_PICTURE'], 'PREVIEW_TEXT' => $arSrc['~PREVIEW_TEXT'], 'PREVIEW_TEXT_TYPE' => $arSrc['PREVIEW_TEXT_TYPE'], 'DETAIL_TEXT' => $arSrc['~DETAIL_TEXT'], 'DETAIL_TEXT_TYPE' => $arSrc['DETAIL_TEXT_TYPE'], 'DETAIL_PICTURE' => $arSrc['DETAIL_PICTURE'], 'WF_STATUS_ID' => $arSrc['WF_STATUS_ID'], 'CODE' => $arSrc['~CODE'], 'TAGS' => $arSrc['~TAGS'], 'XML_ID' => $arSrc['~XML_ID'], 'PROPERTY_VALUES' => array());
                            if ($arDestIBFields['CODE']['IS_REQUIRED'] == 'Y') {
                                if (!strlen($arSrc['CODE'])) {
                                    $arSrc['CODE'] = mt_rand(100000, 1000000);
                                }
                            }
                            if ($arDestIBFields['CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                                $boolElCodeUnique = $boolCodeUnique;
                                if (!$boolCodeUnique) {
                                    $rsCheckItems = CIBlockElement::GetList(array(), array('IBLOCK_ID' => $intDestIBlockID, '=CODE' => $arSrc['CODE'], 'CHECK_PERMISSIONS' => 'N'), false, array('nTopCount' => 1), array('ID', 'IBLOCK_ID'));
                                    if ($arCheck = $rsCheckItems->Fetch()) {
                                        $boolElCodeUnique = true;
                                    }
                                }
                                if ($boolElCodeUnique) {
                                    $arSrc['CODE'] .= mt_rand(100, 10000);
                                }
                            }
                            if ($intSetSectID > 0) {
                                $arSrc['IBLOCK_SECTION_ID'] = $intSetSectID;
                            } elseif ($intSrcIBlockID == $intDestIBlockID) {
                                $arSectionList = array();
                                $rsSections = CIBlockElement::GetElementGroups($ID, true);
                                while ($arSection = $rsSections->Fetch()) {
                                    $arSectionList[] = $arSection['ID'];
                                }
                                $arSrc['IBLOCK_SECTION'] = $arSectionList;
                            }
                            if ($intSrcIBlockID != $intDestIBlockID) {
                                if (empty($arPropListCache)) {
                                    $rsProps = CIBlockProperty::GetList(array(), array('IBLOCK_ID' => $intDestIBlockID, 'PROPERTY_TYPE' => 'L', 'ACTIVE' => 'Y', 'CHECK_PERMISSIONS' => 'N'));
                                    while ($arProp = $rsProps->Fetch()) {
                                        $arValueList = array();
                                        $arNameList = array();
                                        $rsValues = CIBlockProperty::GetPropertyEnum($arProp['ID']);
                                        while ($arValue = $rsValues->Fetch()) {
                                            $arValueList[$arValue['XML_ID']] = $arValue['ID'];
                                            $arNameList[$arValue['ID']] = trim($arValue['VALUE']);
                                        }
                                        if (!empty($arValueList)) {
                                            $arPropListCache[$arProp['CODE']] = $arValueList;
                                        }
                                        if (!empty($arNameList)) {
                                            $arNamePropListCache[$arProp['CODE']] = $arNameList;
                                        }
                                    }
                                }
                                if (empty($arOldPropListCache)) {
                                    $rsProps = CIBlockProperty::GetList(array(), array('IBLOCK_ID' => $intSrcIBlockID, 'PROPERTY_TYPE' => 'L', 'ACTIVE' => 'Y', 'CHECK_PERMISSIONS' => 'N'));
                                    while ($arProp = $rsProps->Fetch()) {
                                        $arValueList = array();
                                        $arNameList = array();
                                        $rsValues = CIBlockProperty::GetPropertyEnum($arProp['ID']);
                                        while ($arValue = $rsValues->Fetch()) {
                                            $arValueList[$arValue['ID']] = $arValue['XML_ID'];
                                            $arNameList[$arValue['ID']] = trim($arValue['VALUE']);
                                        }
                                        if (!empty($arValueList)) {
                                            $arOldPropListCache[$arProp['CODE']] = $arValueList;
                                        }
                                        if (!empty($arNameList)) {
                                            $arOldNamePropListCache[$arProp['CODE']] = $arNameList;
                                        }
                                    }
                                }
                            }
                            foreach ($arSrcPr as &$arProp) {
                                if ($arProp['USER_TYPE'] == 'HTML') {
                                    if (is_array($arProp['~VALUE'])) {
                                        if ($arProp['MULTIPLE'] == 'N') {
                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array('VALUE' => array('TEXT' => $arProp['~VALUE']['TEXT'], 'TYPE' => $arProp['~VALUE']['TYPE']));
                                            if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']]['DESCRIPTION'] = $arProp['~DESCRIPTION'];
                                            }
                                        } else {
                                            if (!empty($arProp['~VALUE'])) {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                                foreach ($arProp['~VALUE'] as $propValueKey => $propValue) {
                                                    $oneNewValue = array('VALUE' => array('TEXT' => $propValue['TEXT'], 'TYPE' => $propValue['TYPE']));
                                                    if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                        $oneNewValue['DESCRIPTION'] = $arProp['~DESCRIPTION'][$propValueKey];
                                                    }
                                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $oneNewValue;
                                                    unset($oneNewValue);
                                                }
                                                unset($propValue, $propValueKey);
                                            }
                                        }
                                    }
                                } elseif ($arProp['PROPERTY_TYPE'] == 'F') {
                                    if (is_array($arProp['VALUE'])) {
                                        $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                        foreach ($arProp['VALUE'] as $propValueKey => $file) {
                                            if ($file > 0) {
                                                $tmpValue = CFile::MakeFileArray($file);
                                                if (!is_array($tmpValue)) {
                                                    continue;
                                                }
                                                if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                    $tmpValue = array('VALUE' => $tmpValue, 'DESCRIPTION' => $arProp['~DESCRIPTION'][$propValueKey]);
                                                }
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $tmpValue;
                                            }
                                        }
                                    } elseif ($arProp['VALUE'] > 0) {
                                        $tmpValue = CFile::MakeFileArray($arProp['VALUE']);
                                        if (is_array($tmpValue)) {
                                            if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                $tmpValue = array('VALUE' => $tmpValue, 'DESCRIPTION' => $arProp['~DESCRIPTION']);
                                            }
                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $tmpValue;
                                        }
                                    }
                                } elseif ($arProp['PROPERTY_TYPE'] == 'L') {
                                    if (!empty($arProp['VALUE_ENUM_ID'])) {
                                        if ($intSrcIBlockID == $arSrc['IBLOCK_ID']) {
                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['VALUE_ENUM_ID'];
                                        } else {
                                            if (isset($arPropListCache[$arProp['CODE']]) && isset($arOldPropListCache[$arProp['CODE']])) {
                                                if (is_array($arProp['VALUE_ENUM_ID'])) {
                                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                                    foreach ($arProp['VALUE_ENUM_ID'] as &$intValueID) {
                                                        $strValueXmlID = $arOldPropListCache[$arProp['CODE']][$intValueID];
                                                        if (isset($arPropListCache[$arProp['CODE']][$strValueXmlID])) {
                                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $arPropListCache[$arProp['CODE']][$strValueXmlID];
                                                        } else {
                                                            $strValueName = $arOldNamePropListCache[$arProp['CODE']][$intValueID];
                                                            $intValueKey = array_search($strValueName, $arNamePropListCache[$arProp['CODE']]);
                                                            if ($intValueKey !== false) {
                                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = $intValueKey;
                                                            }
                                                        }
                                                    }
                                                    if (isset($intValueID)) {
                                                        unset($intValueID);
                                                    }
                                                    if (empty($arSrc['PROPERTY_VALUES'][$arProp['CODE']])) {
                                                        unset($arSrc['PROPERTY_VALUES'][$arProp['CODE']]);
                                                    }
                                                } else {
                                                    $strValueXmlID = $arOldPropListCache[$arProp['CODE']][$arProp['VALUE_ENUM_ID']];
                                                    if (isset($arPropListCache[$arProp['CODE']][$strValueXmlID])) {
                                                        $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arPropListCache[$arProp['CODE']][$strValueXmlID];
                                                    } else {
                                                        $strValueName = $arOldNamePropListCache[$arProp['CODE']][$arProp['VALUE_ENUM_ID']];
                                                        $intValueKey = array_search($strValueName, $arNamePropListCache[$arProp['CODE']]);
                                                        if ($intValueKey !== false) {
                                                            $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $intValueKey;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } elseif ($arProp['PROPERTY_TYPE'] == 'S' || $arProp['PROPERTY_TYPE'] == 'N') {
                                    if ($arProp['MULTIPLE'] == 'Y') {
                                        if (is_array($arProp['~VALUE'])) {
                                            if ($arProp['WITH_DESCRIPTION'] == 'Y') {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = array();
                                                foreach ($arProp['~VALUE'] as $propValueKey => $propValue) {
                                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']][] = array('VALUE' => $propValue, 'DESCRIPTION' => $arProp['~DESCRIPTION'][$propValueKey]);
                                                }
                                                unset($propValue, $propValueKey);
                                            } else {
                                                $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['~VALUE'];
                                            }
                                        }
                                    } else {
                                        $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['WITH_DESCRIPTION'] == 'Y' ? array('VALUE' => $arProp['~VALUE'], 'DESCRIPTION' => $arProp['~DESCRIPTION']) : $arProp['~VALUE'];
                                    }
                                } else {
                                    $arSrc['PROPERTY_VALUES'][$arProp['CODE']] = $arProp['~VALUE'];
                                }
                            }
                            if (isset($arProp)) {
                                unset($arProp);
                            }
                            AddMessage2Log($arSrc['PROPERTY_VALUES']);
                            $intNewID = $el->Add($arSrc, true, true, true);
                            if ($intNewID) {
                                if ($boolCatalog && $boolCopyCatalog) {
                                    $priceRes = CPrice::GetListEx(array(), array('PRODUCT_ID' => $ID), false, false, array('PRODUCT_ID', 'EXTRA_ID', 'CATALOG_GROUP_ID', 'PRICE', 'CURRENCY', 'QUANTITY_FROM', 'QUANTITY_TO'));
                                    while ($arPrice = $priceRes->Fetch()) {
                                        $arPrice['PRODUCT_ID'] = $intNewID;
                                        CPrice::Add($arPrice);
                                    }
                                }
                                if ($boolCatalog && $boolNewCatalog) {
                                    $arProduct = array('ID' => $intNewID);
                                    if ($boolCopyCatalog) {
                                        $productRes = CCatalogProduct::GetList(array(), array('ID' => $ID), false, false, array('QUANTITY', 'QUANTITY_TRACE_ORIG', 'CAN_BUY_ZERO_ORIG', 'NEGATIVE_AMOUNT_TRACE_ORIG', 'SUBSCRIBE_ORIG', 'WEIGHT', 'PRICE_TYPE', 'RECUR_SCHEME_TYPE', 'RECUR_SCHEME_LENGTH', 'TRIAL_PRICE_ID', 'WITHOUT_ORDER', 'SELECT_BEST_PRICE', 'VAT_ID', 'VAT_INCLUDED', 'WIDTH', 'LENGTH', 'HEIGHT', 'PURCHASING_PRICE', 'PURCHASING_CURRENCY', 'MEASURE'));
                                        if ($arCurProduct = $productRes->Fetch()) {
                                            $arProduct = $arCurProduct;
                                            $arProduct['ID'] = $intNewID;
                                            $arProduct['QUANTITY_TRACE'] = $arProduct['QUANTITY_TRACE_ORIG'];
                                            $arProduct['CAN_BUY_ZERO'] = $arProduct['CAN_BUY_ZERO_ORIG'];
                                            $arProduct['NEGATIVE_AMOUNT_TRACE'] = $arProduct['NEGATIVE_AMOUNT_TRACE_ORIG'];
                                            if (isset($arProduct['SUBSCRIBE_ORIG'])) {
                                                $arProduct['SUBSCRIBE'] = $arProduct['SUBSCRIBE_ORIG'];
                                            }
                                            foreach ($arProduct as $productKey => $productValue) {
                                                if ($productValue === null) {
                                                    unset($arProduct[$productKey]);
                                                }
                                            }
                                        }
                                    }
                                    CCatalogProduct::Add($arProduct, false);
                                }
                                if ($_REQUEST['action'] == 'asd_move') {
                                    if (CASDIblockRights::IsElementDelete($intSrcIBlockID, $ID)) {
                                        $el->Delete($ID);
                                    } else {
                                        CASDiblock::$error .= '[' . $ID . '] ' . GetMessage('ASD_ACTION_ERR_DELETE_ELEMENT_RIGHTS') . "\n";
                                    }
                                }
                            } else {
                                CASDiblock::$error .= '[' . $ID . '] ' . $el->LAST_ERROR . "\n";
                            }
                        }
                    }
                    if ($boolCreateSection && $boolCopySect) {
                        if ($_REQUEST['action'] == 'asd_move') {
                            continue;
                        }
                        $rsSections = CIBlockSection::GetList(array(), array('ID' => $ID, 'IBLOCK_ID' => $intSrcIBlockID), false, array('ID', 'NAME', 'XML_ID', 'CODE', 'IBLOCK_SECTION_ID', 'IBLOCK_ID', 'ACTIVE', 'SORT', 'PICTURE', 'DESCRIPTION', 'DESCRIPTION_TYPE', 'DETAIL_PICTURE', 'SOCNET_GROUP_ID', 'UF_*'));
                        if ($arSrcSect = $rsSections->Fetch()) {
                            $arDestSect = $arSrcSect;
                            unset($arDestSect['ID']);
                            $arDestSect['IBLOCK_ID'] = $intDestIBlockID;
                            if ($arDestIBFields['SECTION_CODE']['IS_REQUIRED'] == 'Y') {
                                if (!strlen($arDestSect['CODE'])) {
                                    $arDestSect['CODE'] = mt_rand(100000, 1000000);
                                }
                            }
                            if ($arDestIBFields['SECTION_CODE']['DEFAULT_VALUE']['UNIQUE'] == 'Y') {
                                $boolScCodeUnique = $boolSectCodeUnique;
                                if (!$boolSectCodeUnique) {
                                    $rsCheckItems = CIBlockElement::GetList(array(), array('IBLOCK_ID' => $intDestIBlockID, '=CODE' => $arSrc['CODE'], 'CHECK_PERMISSIONS' => 'N'), false, array('nTopCount' => 1), array('ID', 'IBLOCK_ID'));
                                    if ($arCheck = $rsCheckItems->Fetch()) {
                                        $boolScCodeUnique = true;
                                    }
                                }
                                if ($boolScCodeUnique) {
                                    $arDestSect['CODE'] .= mt_rand(100, 10000);
                                }
                            }
                            if ($intSetSectID > 0) {
                                $arDestSect['IBLOCK_SECTION_ID'] = $intSetSectID;
                            } elseif ($intSrcIBlockID != $intDestIBlockID) {
                                $arDestSect['IBLOCK_SECTION_ID'] = 0;
                            }
                            $arDestSect['PICTURE'] = (int) $arDestSect['PICTURE'];
                            if ($arDestSect['PICTURE'] > 0) {
                                $arDestSect['PICTURE'] = CFile::MakeFileArray($arDestSect['PICTURE']);
                                if (empty($arDestSect['PICTURE'])) {
                                    $arDestSect['PICTURE'] = false;
                                } else {
                                    $arDestSect['PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arDestSect['PICTURE'] = false;
                            }
                            $arDestSect['DETAIL_PICTURE'] = (int) $arDestSect['DETAIL_PICTURE'];
                            if ($arDestSect['DETAIL_PICTURE'] > 0) {
                                $arDestSect['DETAIL_PICTURE'] = CFile::MakeFileArray($arDestSect['DETAIL_PICTURE']);
                                if (empty($arDestSect['DETAIL_PICTURE'])) {
                                    $arDestSect['DETAIL_PICTURE'] = false;
                                } else {
                                    $arDestSect['DETAIL_PICTURE']['COPY_FILE'] = 'Y';
                                }
                            } else {
                                $arDestSect['DETAIL_PICTURE'] = false;
                            }
                            if (!$boolUFListCache) {
                                $boolUFListCache = true;
                                $arUFListCache = $USER_FIELD_MANAGER->GetUserFields('IBLOCK_' . $intDestIBlockID . '_SECTION');
                                if (!empty($arUFListCache)) {
                                    if ($intSrcIBlockID != $intDestIBlockID) {
                                        $arOldUFListCache = $USER_FIELD_MANAGER->GetUserFields('IBLOCK_' . $intSrcIBlockID . '_SECTION');
                                        if (empty($arOldUFListCache)) {
                                            $arUFListCache = array();
                                        }
                                    } else {
                                        $arOldUFListCache = $arUFListCache;
                                    }
                                }
                                if (!empty($arUFListCache)) {
                                    if ($intSrcIBlockID != $intDestIBlockID) {
                                        foreach ($arUFListCache as &$arOneUserField) {
                                            if ('enum' == $arOneUserField['USER_TYPE']['BASE_TYPE']) {
                                                $arUFEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $arUFNameEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $rsEnum = $obEnum->GetList(array(), array('USER_FIELD_ID' => $arOneUserField['ID']));
                                                while ($arEnum = $rsEnum->Fetch()) {
                                                    $arUFEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['XML_ID']] = $arEnum['ID'];
                                                    $arUFNameEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['ID']] = trim($arEnum['VALUE']);
                                                }
                                            }
                                        }
                                        if (isset($arOneUserField)) {
                                            unset($arOneUserField);
                                        }
                                        foreach ($arOldUFListCache as &$arOneUserField) {
                                            if ($arOneUserField['USER_TYPE']['BASE_TYPE'] == 'enum') {
                                                $arOldUFEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']] = array();
                                                $rsEnum = $obEnum->GetList(array(), array('USER_FIELD_ID' => $arOneUserField['ID']));
                                                while ($arEnum = $rsEnum->Fetch()) {
                                                    $arOldUFEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['ID']] = $arEnum['XML_ID'];
                                                    $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']][$arEnum['ID']] = trim($arEnum['VALUE']);
                                                }
                                            }
                                        }
                                        if (isset($arOneUserField)) {
                                            unset($arOneUserField);
                                        }
                                    }
                                }
                            }
                            if (!empty($arUFListCache)) {
                                foreach ($arUFListCache as &$arOneUserField) {
                                    if (!isset($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                        continue;
                                    }
                                    if ($arOneUserField['USER_TYPE']['BASE_TYPE'] == 'file') {
                                        if (!empty($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                            if (is_array($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                                $arNewFileList = array();
                                                foreach ($arDestSect[$arOneUserField['FIELD_NAME']] as &$intFileID) {
                                                    $arNewFile = false;
                                                    $intFileID = (int) $intFileID;
                                                    if ($intFileID > 0) {
                                                        $arNewFile = CFile::MakeFileArray($intFileID);
                                                    }
                                                    if (!empty($arNewFile)) {
                                                        $arNewFileList[] = $arNewFile;
                                                    }
                                                }
                                                if (isset($intFileID)) {
                                                    unset($intFileID);
                                                }
                                                $arDestSect[$arOneUserField['FIELD_NAME']] = !empty($arNewFileList) ? $arNewFileList : false;
                                            } else {
                                                $arNewFile = false;
                                                $intFileID = (int) $arDestSect[$arOneUserField['FIELD_NAME']];
                                                if ($intFileID > 0) {
                                                    $arNewFile = CFile::MakeFileArray($intFileID);
                                                }
                                                $arDestSect[$arOneUserField['FIELD_NAME']] = !empty($arNewFile) ? $arNewFile : false;
                                            }
                                        } else {
                                            $arDestSect[$arOneUserField['FIELD_NAME']] = false;
                                        }
                                    } elseif ($arOneUserField['USER_TYPE']['BASE_TYPE'] == 'enum') {
                                        if (!empty($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                            if ($intSrcIBlockID != $intDestIBlockID) {
                                                if (array_key_exists($arOneUserField['FIELD_NAME'], $arUFEnumCache) && array_key_exists($arOneUserField['FIELD_NAME'], $arOldUFEnumCache)) {
                                                    if (is_array($arDestSect[$arOneUserField['FIELD_NAME']])) {
                                                        $arNewEnumList = array();
                                                        foreach ($arDestSect[$arOneUserField['FIELD_NAME']] as &$intValueID) {
                                                            $strValueXmlID = $arOldUFEnumCache[$arOneUserField['FIELD_NAME']][$intValueID];
                                                            if (array_key_exists($strValueXmlID, $arUFEnumCache[$arOneUserField['FIELD_NAME']])) {
                                                                $arNewEnumList[] = $arUFEnumCache[$arOneUserField['FIELD_NAME']][$strValueXmlID];
                                                            } else {
                                                                $strValueName = $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']][$intValueID];
                                                                $intValueKey = array_search($strValueName, $arUFNameEnumCache[$arOneUserField['FIELD_NAME']]);
                                                                if ($intValueKey !== false) {
                                                                    $arNewEnumList[] = $intValueKey;
                                                                }
                                                            }
                                                        }
                                                        if (isset($intValueID)) {
                                                            unset($intValueID);
                                                        }
                                                        if (!empty($arNewEnumList)) {
                                                            $arDestSect[$arOneUserField['FIELD_NAME']] = $arNewEnumList;
                                                        }
                                                    } else {
                                                        $strValueXmlID = $arOldUFEnumCache[$arOneUserField['FIELD_NAME']][$arDestSect[$arOneUserField['FIELD_NAME']]];
                                                        if (array_key_exists($strValueXmlID, $arUFEnumCache[$arOneUserField['FIELD_NAME']])) {
                                                            $arDestSect[$arOneUserField['FIELD_NAME']] = $arUFEnumCache[$arOneUserField['FIELD_NAME']][$strValueXmlID];
                                                        } else {
                                                            $strValueName = $arOldUFNameEnumCache[$arOneUserField['FIELD_NAME']][$arDestSect[$arOneUserField['FIELD_NAME']]];
                                                            $intValueKey = array_search($strValueName, $arUFNameEnumCache[$arOneUserField['FIELD_NAME']]);
                                                            if ($intValueKey !== false) {
                                                                $arDestSect[$arOneUserField['FIELD_NAME']] = $intValueKey;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        } else {
                                            $arDestSect[$arOneUserField['FIELD_NAME']] = false;
                                        }
                                    }
                                }
                                if (isset($arOneUserField)) {
                                    unset($arOneUserField);
                                }
                            }
                            $intNewID = $sc->Add($arDestSect);
                            if (!$intNewID) {
                                CASDiblock::$error .= '[' . $ID . '] ' . $sc->LAST_ERROR . "\n";
                            }
                        }
                    }
                }
                $successRedirect = true;
            }
            unset($_REQUEST['action']);
            if (isset($_REQUEST['action_button'])) {
                unset($_REQUEST['action_button']);
            }
            if ($successRedirect) {
                LocalRedirect($GLOBALS['APPLICATION']->GetCurPageParam('', array('action', 'action_button', 'asd_ib_dest', 'asd_sect_dest', 'ID')));
            }
        }
        if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'asd_remove' && $IBLOCK_ID > 0 && isset($_REQUEST['find_section_section']) && check_bitrix_sessid() && CASDIblockRights::IsIBlockDisplay($IBLOCK_ID)) {
            $intSectionID = (int) $_REQUEST['find_section_section'];
            if ($intSectionID > 0) {
                $strCurPage = $GLOBALS['APPLICATION']->GetCurPage();
                $bElemPage = $strCurPage == '/bitrix/admin/iblock_element_admin.php' || $strCurPage == '/bitrix/admin/cat_product_admin.php';
                $bMixPage = $strCurPage == '/bitrix/admin/iblock_list_admin.php';
                if ($bElemPage || $bMixPage) {
                    foreach ($_REQUEST['ID'] as $eID) {
                        if ($bMixPage) {
                            if (substr($eID, 0, 1) != 'E') {
                                continue;
                            }
                            $ID = (int) substr($eID, 1);
                        } else {
                            $ID = (int) $eID;
                        }
                        if ($ID <= 0) {
                            continue;
                        }
                        if (CASDIblockRights::IsElementEdit($IBLOCK_ID, $ID)) {
                            $arSectionList = array();
                            $rsSections = CIBlockElement::GetElementGroups($ID, true);
                            while ($arSection = $rsSections->Fetch()) {
                                $arSection['ID'] = (int) $arSection['ID'];
                                if ($arSection['ID'] != $intSectionID) {
                                    $arSectionList[] = $arSection['ID'];
                                }
                            }
                            CIBlockElement::SetElementSection($ID, $arSectionList, false);
                            $successRedirect = true;
                        }
                    }
                }
            }
            unset($_REQUEST['action']);
            if (isset($_REQUEST['action_button'])) {
                unset($_REQUEST['action_button']);
            }
            if ($successRedirect) {
                LocalRedirect($GLOBALS['APPLICATION']->GetCurPageParam('', array('action', 'action_button')));
            }
        }
    }
                 }
             }
             foreach ($arFields as $key => $value) {
                 if (isset($value["PRICE"])) {
                     $value["PRICE"] = str_replace(",", ".", Trim($value["PRICE"]));
                     $value["PRICE"] = preg_replace("/[^\\d.]/i", "", $value["PRICE"]);
                     $value["PRICE"] = DoubleVal($value["PRICE"]);
                 } else {
                     $value["PRICE"] = false;
                 }
                 $value["TMP_ID"] = $tmpid;
                 $res = CPrice::GetList(array(), array("PRODUCT_ID" => $PRODUCT_ID, "CATALOG_GROUP_ID" => $key, "QUANTITY_FROM" => $quantityFrom, "QUANTITY_TO" => $quantityTo));
                 if ($arr = $res->Fetch()) {
                     CPrice::Update($arr["ID"], $value);
                 } else {
                     CPrice::Add($value);
                 }
             }
         }
         if (strlen($strErrorR) <= 0) {
             $correct_lines++;
         } else {
             $error_lines++;
             $strImportErrorMessage .= $strErrorR;
         }
         if (!($bAllLinesLoaded = CSVCheckTimeout($max_execution_time))) {
             break;
         }
     } while ($arRes = $csvFile->Fetch());
 }
 //////////////////////////////
					"CATALOG_GROUP_ID" => $PRICE_ID,
					"PRICE" => $OFFER_PRICE,
					"CURRENCY" => $OFFER_CURRENCY
				);

			$res = CPrice::GetList(
					array(),
					array(
							"PRODUCT_ID" => $PRODUCT_ID,
							"CATALOG_GROUP_ID" => $PRICE_ID
						)
				);
			if ($arr = $res->Fetch())
				$khjk = CPrice::Update($arr["ID"], $arFields);
			else
				$khjk = CPrice::Add($arFields);
		}
	}

	if (COption::GetOptionString("catalog", "deactivate_1c_no_price", "N")=="Y")
	{
		foreach ($arProductsTmpA as $keyA=>$valA)
		{
			foreach ($valA["arProducts"] as $keyB=>$valB)
			{
				$res = $el->Update(IntVal($valB), Array("ACTIVE" => "N"));
			}
		}
	}

	$strImportOKMessage .= str_replace("#TIME#", RoundEx(getmicrotime() - $startImportExecTime, 2), GetMessage("CICML_LOAD_TIME"))."<br>";
     }
     if (strlen($lang) <= 0) {
         $lang = "ru";
     }
     $defCurrency = "EUR";
     if ($lang == "ru") {
         $shopLocalization = $wizard->GetVar("shopLocalization");
         if ($shopLocalization == "ua") {
             $defCurrency = "UAH";
         } else {
             $defCurrency = "RUB";
         }
     } elseif ($lang == "en") {
         $defCurrency = "USD";
     }
     $elementPrice = CPrice::Add(array("PRODUCT_ID" => $elementID, "PRICE" => $arOffer["PRICE"], "CURRENCY" => $defCurrency, "CATALOG_GROUP_ID" => "1"));
 }
 // form settings
 /*	$f1 = 'edit1--#--'.GetMessage("WZD_OPTION_CATALOG_1").'--,--ACTIVE--#--'.GetMessage("WZD_OPTION_CATALOG_2").'--,--NAME--#--'.GetMessage("WZD_OPTION_CATALOG_3").'--,--CODE--#--'.GetMessage("WZD_OPTION_CATALOG_4").'--,--DETAIL_PICTURE--#--'.GetMessage("WZD_OPTION_CATALOG_5").'--,';
 	$f1 .= $fProps;
 	if(CCatalog::GetByID($arIBlockFur["ID"]) && CCatalog::GetByID($IBLOCK_OFFERS_ID)) 
 	{
 	
 		$f1 .= '--CATALOG--#--'.GetMessage("WZD_OPTION_CATALOG_20").'--;--cedit1--#--'.GetMessage("WZD_OPTION_CATALOG_27").'--,--PREVIEW_TEXT--#--'.GetMessage("WZD_OPTION_CATALOG_6").'--,--DETAIL_TEXT--#--'.GetMessage("WZD_OPTION_CATALOG_7").'--,--cedit1_csection1--#----'.GetMessage("WZD_OPTION_CATALOG_9").'--,--SECTIONS--#--'.GetMessage("WZD_OPTION_CATALOG_30").'--;--';
 		$f1 .= 'cedit2--#--'.GetMessage("WZD_OPTION_CATALOG_31").'--,--OFFERS--#--'.GetMessage("WZD_OPTION_CATALOG_31").'--;--';
 	}
 	else 
 	{
 		$f1 .= '--OFFERS--#--'.GetMessage("WZD_OPTION_CATALOG_20").'--;--cedit1--#--'.GetMessage("WZD_OPTION_CATALOG_27").'--,--PREVIEW_TEXT--#--'.GetMessage("WZD_OPTION_CATALOG_6").'--,--DETAIL_TEXT--#--'.GetMessage("WZD_OPTION_CATALOG_7").'--,--cedit1_csection1--#----'.GetMessage("WZD_OPTION_CATALOG_9").'--,--SECTIONS--#--'.GetMessage("WZD_OPTION_CATALOG_30").'--;--';			
 	}    */
 //	CUserOptions::SetOption("form", "form_element_".$arIBlockFur["ID"], array ( 'tabs' => $f1, ));
Beispiel #14
0
	function SetBasePrice($ProductID, $Price, $Currency, $quantityFrom = false, $quantityTo = false, $bGetID = false)
	{
		$bGetID = ($bGetID == true);

		$arFields = array();
		$arFields["PRICE"] = doubleval($Price);
		$arFields["CURRENCY"] = $Currency;
		$arFields["QUANTITY_FROM"] = ($quantityFrom == false ? false : (int)$quantityFrom);
		$arFields["QUANTITY_TO"] = ($quantityTo == false ? false : (int)$quantityTo);
		$arFields["EXTRA_ID"] = false;

		$ID = false;
		if ($arBasePrice = CPrice::GetBasePrice($ProductID, $quantityFrom, $quantityTo, false))
		{
			$ID = CPrice::Update($arBasePrice["ID"], $arFields);
		}
		else
		{
			$arBaseGroup = CCatalogGroup::GetBaseGroup();
			$arFields["CATALOG_GROUP_ID"] = $arBaseGroup["ID"];
			$arFields["PRODUCT_ID"] = $ProductID;

			$ID = CPrice::Add($arFields);
		}
		if (!$ID)
		{
			return false;
		}
		else
		{
			return ($bGetID ? $ID : true);
		}
	}
                            break;
                    }
                }
            }
            $arPropertySaveValues["CML2_LINK"] = $parentElement;
            $arIBlockElementAdd['PROPERTY_VALUES'] = $arPropertySaveValues;
            $sku = new \Bitrix\Iblock\Template\Entity\Element(0);
            $sku->setFields($arIBlockElementAdd);
            $arIBlockElementAdd["NAME"] = htmlspecialcharsback(\Bitrix\Iblock\Template\Engine::process($sku, $title));
            unset($arIBlockElementAdd['PROPERTY_VALUES']["CML2_LINK"]);
            $idNewElement = $obIBlockElement->Add($arIBlockElementAdd, false, true, true);
            if ($idNewElement) {
                $productData['ID'] = $idNewElement;
                CCatalogProduct::Add($productData, false);
                foreach ($arPriceGroup as $price) {
                    CPrice::Add(array("PRODUCT_ID" => $idNewElement, "CURRENCY" => $price["CURRENCY"], "PRICE" => $price["PRICE"], "CATALOG_GROUP_ID" => $price["TYPE"]));
                }
                $element = new \Bitrix\Iblock\InheritedProperty\ElementValues($subIBlockId, $idNewElement);
                $template = new \Bitrix\Iblock\InheritedProperty\BaseTemplate($element);
                $template->set(array("MY_TEMPLATE" => $title));
            } else {
                $errorMessage .= $obIBlockElement->LAST_ERROR;
                break;
            }
        }
        unset($productData);
        if ($idNewElement) {
            ?>
			<script type="text/javascript">
				top.BX.closeWait();
				if (!!top.BX.WindowManager.Get())
Beispiel #16
0
	/**
	 * [addPriceProducts description]
	 * @param array $arParams
	 * @return bool
	 */
	protected function addPriceProducts($arParams){
		if (!CModule::IncludeModule("iblock") && !CModule::IncludeModule("catalog") && !CModule::IncludeModule("sale")):
			return false;
		endif;
		$PRICE_TYPE_ID = 1; // идентификатор типы базовой цены
		$arFields = Array(
		    "PRODUCT_ID" => $arParams["PRODUCT_ID"],
		    "CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
		    "PRICE" => $arParams["OLD_PRICE"],
		    "CURRENCY" => "RUB",
		    "QUANTITY_FROM" => 1,
		);
		$res = CPrice::GetList(
		        array(),
		        array(
	                "PRODUCT_ID" => $arParams["PRODUCT_ID"],
	                "CATALOG_GROUP_ID" => $PRICE_TYPE_ID
	            )
		    );
		if ($arr = $res->Fetch()):
		    if (!CPrice::Update($arr["ID"], $arFields)):
		    	return false;
		    endif;
		else:
		    if (!CPrice::Add($arFields)):
		    	return false;
		    endif;
		endif;
		if (!$this->addCatalogProducts($arParams)):
			return false;
		endif;
		return true;
	}
Beispiel #17
0
 function SetBasePrice($ProductID, $Price, $Currency, $quantityFrom = 0, $quantityTo = 0, $bGetID = false)
 {
     global $DB;
     $bGetID = $bGetID == true ? true : false;
     $arFields = array();
     $arFields["PRICE"] = DoubleVal($Price);
     $arFields["CURRENCY"] = $Currency;
     $arFields["QUANTITY_FROM"] = IntVal($quantityFrom);
     $arFields["QUANTITY_TO"] = IntVal($quantityTo);
     $arFields["EXTRA_ID"] = False;
     $ID = false;
     if ($arBasePrice = CPrice::GetBasePrice($ProductID, $quantityFrom, $quantityTo)) {
         //CPrice::Update($arBasePrice["ID"], $arFields);
         $ID = CPrice::Update($arBasePrice["ID"], $arFields);
     } else {
         $arBaseGroup = CCatalogGroup::GetBaseGroup();
         $arFields["CATALOG_GROUP_ID"] = $arBaseGroup["ID"];
         $arFields["PRODUCT_ID"] = $ProductID;
         //CPrice::Add($arFields);
         $ID = CPrice::Add($arFields);
     }
     if (!$ID) {
         return false;
     } else {
         return $bGetID ? $ID : true;
     }
 }