Обучаю битриксу программистов, интеграторов

Фильтр товаров по скидкам

Задача:
Вывести товары по определенной скидке

Компонент формирует фильтр. Делала давно, наверняка, уже не работает, но оставлю на память
component.php
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();
//@var array $arParams
//@var array $arResult 

$arParams["FILTER_NAME"] = trim($arParams["FILTER_NAME"]);
if ($arParams["FILTER_NAME"] === '' || !preg_match("/^[A-Za-z_][A-Za-z01-9_]*$/", $arParams["FILTER_NAME"])){
    $arParams["FILTER_NAME"] = "arrFilter";
}
global ${$arParams['FILTER_NAME']};
$arrFilter = &${$arParams['FILTER_NAME']};

if ($this->StartResultCache()){
    
    if(!CModule::IncludeModule("catalog")) {
       $this->AbortResultCache();
       ShowError("CATALOG_MODULE_NOT_INSTALLED");
       return false;
    }

    if(!CModule::IncludeModule("iblock")) {
       $this->AbortResultCache();
       ShowError("IBLOCK_MODULE_NOT_INSTALLED");
       return false;
    }
    include('functions.php');

    //////////////////////////////////////////////////////////////////
    //                get start data                                //
    //////////////////////////////////////////////////////////////////

    $arFilter = array('ACTIVE'=>'Y',
                       "!>ACTIVE_FROM" => $DB->FormatDate(date("Y-m-d H:i:s"), 
                                               "YYYY-MM-DD HH:MI:SS",
                                               CSite::GetDateFormat("FULL")),
                        "!<ACTIVE_TO" => $DB->FormatDate(date("Y-m-d H:i:s"), 
                                             "YYYY-MM-DD HH:MI:SS", 
                                             CSite::GetDateFormat("FULL"))
                        );
    if(count($arParams['DISCOUNT_ID'])>0){
        $arFilter['=ID'] = $arParams['DISCOUNT_ID'];      
    }    
    $dbDiscount = CCatalogDiscount::GetList(array(), $arFilter, false, false, array());

    $catalogInfo = CCatalog::GetByID($arParams["IBLOCK_ID"]);
    if($catalogInfo === false){
        $catalogInfo = CIBlockPriceTools::GetOffersIBlock($arParams["IBLOCK_ID"]);
        $catalogInfo ["IBLOCK_ID"] =  $arParams["IBLOCK_ID"];        
    }    
    $arrFilterTemp = array('LOGIC'=>'OR');
    $firstConditions = TRUE; 
    $idDiscount = array();
    $priceTypeId = array();
    if(array_key_exists("PRICE_CODE", $arParams) and is_array($arParams["PRICE_CODE"]) and count($arParams["PRICE_CODE"])>0){
        $dbPriceType = CCatalogGroup::GetList(
                array("SORT" => "ASC"),
                array("NAME" => $arParams["PRICE_CODE"])
        );        
        while ($arPriceType = $dbPriceType->Fetch()){
            $priceTypeId[] = $arPriceType['ID'];
        }
    }


    //////////////////////////////////////////////////////////////////
    //                work with data                                //
    //////////////////////////////////////////////////////////////////

    while($discount = $dbDiscount->Fetch()){         
        if(!in_array($discount['ID'], $idDiscount)){            
            $conditions = unserialize($discount['CONDITIONS']);
            $idDiscount[] = $discount['ID'];
            if (is_array($conditions) && !empty($conditions) && $firstConditions){
                $obCond = new CCatalogCondTree();
                $boolCond = $obCond->Init(BT_COND_MODE_SEARCH, BT_COND_BUILD_CATALOG, array());
                $firstConditions = FALSE;                 
            }
            $arrFilterTemp[] = MakeFilter(
                array(
                    "CONDITIONS" => $conditions,
                    "OB_COND" => $obCond,
                    "CATALOG_INFO" => $catalogInfo                  
                )
            );
        } 
    }    
    if(count($arrFilterTemp)==1){
        $arrFilter = array('IBLOCK_ID'=>$arParams["IBLOCK_ID"],'ID'=>'-1'); 
    }
    else{      
        if(count($priceTypeId)>0){
            //добавляем условие в АрФильтр, чтобы товары с нулевыми ценами не выводились
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if($catalogInfo["OFFERS_IBLOCK_ID"] == ""){
                //нет офферсов, тогда только по цене каталога фильтруем
                $arTemp = array('LOGIC'=>'OR');
                foreach ($priceTypeId as $key => $price) {
                    $arTemp[">CATALOG_PRICE_".$price] = 0;    
                }  
                $arrFilterTemp= array('LOGIC'=>'AND', $arrFilterTemp, $arTemp);               
            }
            elseif(!array_key_exists("ID", $catalogInfo)){
                //есть офферсы, которые являются торговым каталогом, а сам инфоблок не является торговым каталогом                               
                $filterSubQuery =  array(
                       "IBLOCK_ID" => $catalogInfo['OFFERS_IBLOCK_ID']                
                );                
                $arTemp = array('LOGIC'=>'OR');
                foreach ($priceTypeId as $key => $price) {
                    $arTemp[">CATALOG_PRICE_".$price] = 0;                 
                }
                $filterSubQuery[] = $arTemp;  
                unset($arTemp);                                                                          
                $arTemp['=ID']=CIBlockElement::SubQuery(
                    "PROPERTY_".$catalogInfo['OFFERS_PROPERTY_ID'], 
                    $filterSubQuery
                ); 
                $arrFilterTemp= array('LOGIC'=>'AND', $arrFilterTemp, $arTemp);                    
            }
            else{
                //есть офферсы, которые являются торговым каталогом, и сам инфоблок является торговым каталогом 
                $arTemp1 = array('LOGIC'=>'OR');
                foreach ($priceTypeId as $key => $price) {
                    $arTemp1[">CATALOG_PRICE_".$price] = 0;    
                } 

                $arTemp = array('LOGIC'=>'OR');
                foreach ($priceTypeId as $key => $price) {
                    $arTemp[">CATALOG_PRICE_".$price] = 0;                 
                }
                $filterSubQuery[] = $arTemp;  
                unset($arTemp);                                                                          
                $arTemp['=ID']=CIBlockElement::SubQuery(
                    "PROPERTY_".$catalogInfo['OFFERS_PROPERTY_ID'], 
                    $filterSubQuery
                ); 
                $arrFilterTemp= array('LOGIC'=>'AND', $arrFilterTemp, array('LOGIC'=>'OR',$arTemp, $arTemp1));  
            }
             
            

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }              
        $arrFilter = array('IBLOCK_ID'=>$arParams["IBLOCK_ID"],$arrFilterTemp);     
    }    
    $arResult['DISCOUNT_FILTER'] = $arrFilter;
   /* echo "<pre>";
    print_r($arrFilter);
    echo "</pre>";*/
    $this -> EndResultCache();    
}
else{
    $arrFilter =  $arResult['DISCOUNT_FILTER'];     
}

functions.php
if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();

function GetField($arVars){ 
    $nameField = "";
    $simpleCondition = array(
        'CLASS_ID' => 'CondGroup', 
        'DATA' => array(
            'All'=>'AND',
            'True' => 'True'
        ),
        'CHILDREN' => array(
            array(
                'CLASS_ID'=>$arVars['CLASS_ID'],
                'DATA' => array(
                    'logic'=>'Equal',
                    'value' => $arVars['CONDITION_VALUE']
                )

            )
        )
    );
    $field = $arVars['OB_COND']->GetConditionValues($simpleCondition);
    foreach ($field as $key => $value) {
       $nameField = $value['FIELD']; 
    }        
    unset($field);
    if(stripos($arVars['CLASS_ID'],'CondIBProp:')!== false){            
        $field = explode(":",$arVars['CLASS_ID']);
        if($field[1]==$arVars['IBLOCK_ID']){
            $whoIs="product";
        }
        else{
            $whoIs = "offers";
        }
        $nameFieldTemp = explode("_",$nameField);
        unset($nameFieldTemp[2]);
        $nameField = implode("_",$nameFieldTemp);            
    }
    else{
        $whoIs = 'product';            
    }
    return array('WHO'=>$whoIs, 'NAME'=>$nameField);
}    

function MakeFilter($arVars){
    $conditions = $arVars['CONDITIONS'];
    $catalogInfo = $arVars['CATALOG_INFO'];    
    $logicOperators = array(
        "Equal"=>array('True'=>'=','False'=>'!='),
        "Great"=>array('True'=>'>','False'=>'<='),
        "Not"=>array('True'=>'!=','False'=>'='),
        "Less"=>array('True'=>'<','False'=>'>='),
        "EqGr"=>array('True'=>'>=','False'=>'<'),
        "EqLs"=>array('True'=>'<=','False'=>'>'),
        "Contain"=>array('True'=>'','False'=>'!')
    );
    foreach ($conditions['CHILDREN'] as $key => $children) {            
        $arrFilter['LOGIC']=$conditions['DATA']['All'];
        if ($children['CLASS_ID']=='CondGroup'){ 
            $arrFilter[] = MakeFilter(
                array(
                    "CONDITIONS" => $children, 
                    "OB_COND" => $arVars["OB_COND"],
                    "CATALOG_INFO" => $catalogInfo,                    
                ) 
            );
        }
        else{
            $logic = $logicOperators[$children['DATA']['logic']][$conditions['DATA']['True']];
            $field = GetField(
                array(
                    "OB_COND" => $arVars["OB_COND"], 
                    "CLASS_ID" => $children['CLASS_ID'], 
                    'CONDITION_VALUE' => $children['DATA']['value'],
                    'IBLOCK_ID'=> $catalogInfo['IBLOCK_ID']
                )
            );
            if($field["NAME"] != ""){
                if($field['WHO'] =='offers'){ 
                    $filterSubQuery =  array(
                            "IBLOCK_ID" => $catalogInfo['OFFERS_IBLOCK_ID'],
                            $logic.$field['NAME'] => $children['DATA']['value']                        
                        );                                                                               
                   $arrFilter[]['=ID']=CIBlockElement::SubQuery(
                        "PROPERTY_".$catalogInfo['OFFERS_PROPERTY_ID'], 
                        $filterSubQuery
                    ); 
                }                
                elseif($field['NAME'] == 'SECTION_ID'){
                    $arrFilterTemp[$logic.$field['NAME']][] = $children['DATA']['value'];
                    $arrFilterTemp['INCLUDE_SUBSECTIONS'] = "Y";
                    $arrFilter[] = $arrFilterTemp;
                    unset($arrFilterTemp);                    
                }
                elseif(($field['NAME'] == 'NAME')and ($catalogInfo["OFFERS_IBLOCK_ID"] != "")){
                    $filterSubQuery =  array(
                            "IBLOCK_ID" => $catalogInfo['OFFERS_IBLOCK_ID'],
                            $logic.$field['NAME'] => "%".$children['DATA']['value']."%"                       
                        );                                                                               
                    $arrFilter[]['=ID']=CIBlockElement::SubQuery(
                            "PROPERTY_".$catalogInfo['OFFERS_PROPERTY_ID'], 
                            $filterSubQuery
                    ); 
                }
                elseif ($field['NAME'] == 'NAME') {
                    if($arrFilter['LOGIC']=='OR'){
                        $arrFilter[$logic.$field['NAME']][] = "%".$children['DATA']['value']."%"; 
                    }
                    else{
                        $arrFilter[][$logic.$field['NAME']] = "%".$children['DATA']['value']."%"; 
                    }  
                }
                else{
                    if($arrFilter['LOGIC']=='OR'){
                        $arrFilter[$logic.$field['NAME']][] = $children['DATA']['value'];
                    }
                    else{
                        $arrFilter[][$logic.$field['NAME']] = $children['DATA']['value'];
                    }                    
                }
            }
            
        }
    }      
    if(count($arrFilter)==2){
        unset($arrFilter['LOGIC']);
        if(array_key_exists(0, $arrFilter)){
            $arrFilter=$arrFilter[0];
        }
    }    
    
    return $arrFilter;
}
all.discount.zip (7.13 КБ)
Если блог был полезным, можете угостить меня "чашечкой кофе" :)

Сбер по номеру телефона +7 (953) 585-13-09 Вероника.
Спасибо!