Your IP : 18.189.186.72


Current Path : /home/bitrix/ext_www/dev.ballu.in.ua/local/import/
Upload File :
Current File : /home/bitrix/ext_www/dev.ballu.in.ua/local/import/servicesImport.php

<?php
class servicesImport
{
    /**
     * @var null | static $obj
     */
    protected static $obj=null;
    protected $citiesInDB = null;
    protected $el = null;
    protected $sl = null;
    protected $geo = null;
    protected $cities = null;
    protected $countries = null;
    protected $data = null;
    protected $targetIblock = SERVICES_IBLOCK_ID;
    protected $categories = array();
    protected $messages = array();
    protected $log_file = '';

    public function showMessage(){
        echo (json_encode($this->messages));
    }
    public static function getyInstance()
    {
        if (!static::$obj){
            static::$obj = new static();
        }
        return static::$obj;
    }
    protected function __construct()
    {
        $this->el = new CIBlockElement;
        $this->sl = new CIBlockSection;
        $res = CIBlockElement::GetList(array(), array("IBLOCK_ID" => 5), false, false, array("ID", 'IBLOCK_ID', "NAME", "EXTERNAL_ID", 'PROPERTY_*'));
        $cities = array();
        while($ob = $res->GetNextElement()) {
            $arFields = $ob->GetFields();
            //$citiesT[$arFields['EXTERNAL_ID']] = $arFields;
            $arProps = $ob->GetProperties();
            //$citiesT[$arFields['EXTERNAL_ID']]['PROPERTY'] = $arProps;
            if (!isset($cities[$arProps['COUNTRY']['VALUE']])) {
                $cities[$arProps['COUNTRY']['VALUE']] = array();
            }
            $this->citiesInDB[$arFields['ID']] = $arFields['ID'];
            $cities[$arProps['COUNTRY']['VALUE']][$arFields['EXTERNAL_ID']] = $arFields;
            $cities[$arProps['COUNTRY']['VALUE']][$arFields['NAME']] = &$cities[$arProps['COUNTRY']['VALUE']][$arFields['EXTERNAL_ID']];
        }
        $this->log_file = fopen(dirname(__FILE__).'/logs/'.get_class($this).'.log', "a+");

        $this->cities=$cities;
        $countries=array();
        $res = CIBlockElement::GetList(array(), array("IBLOCK_ID" => 8), false, false, array("ID", 'IBLOCK_ID',  "NAME", "EXTERNAL_ID", 'PROPERTY_*'));
        while($ob = $res->GetNextElement()){
            $arFields = $ob->GetFields();
            $this->countries[$arFields['EXTERNAL_ID']] = $countries[$arFields['EXTERNAL_ID']] = $arFields;
            $arProps = $ob->GetProperties();
            $this->countries[$arFields['EXTERNAL_ID']]['PROPERTY_EBASC_ID'] = $countries[$arFields['EXTERNAL_ID']]['PROPERTY_EBASC_ID'] = $arProps['EBASC_ID']['VALUE'];
        }
        foreach ($countries as $country) {
            $this->geo[$country["PROPERTY_EBASC_ID"]] = array(
                'PROPERTY_EBASC_ID' => $country["PROPERTY_EBASC_ID"],
                'ID' => $country["ID"],
                'NAME' => $country["NAME"],
                'SITIES' => $cities[$country["ID"]]
            );
        }
    }
    public function importGeo(){
		// EBASC_ID
		//Республика Беларусь - 2249037574
		//Республика Казахстан - 1855031256
		//Российская Федерация - 3010322388
		//Украина - 3271033318
        foreach ($this->data->data->countries->country as $country) {
            if (isset($this->geo[$country->id])) {
                $this->importCities($country->id,$country->cities->city);
            }else{
                $this->log('FATAL GEO COUNTRY: dont find country', $country);
                $this->showMessage();
                die();
            }
        }
    }
    public function importCities($country,$cities){
        foreach ($cities as $city) {
            if ($city->name) {
                if (isset($this->geo[$country]['SITIES'][$city->id])) {
                }elseif(isset($this->geo[$country]['SITIES'][$city->name])){
                    $this->geo[$country]['SITIES'][$city->id] = &$this->geo[$country]['SITIES'][$city->name];
                } else {
                    $arFields = array(
                        "IBLOCK_ID" => 5,
                        "ACTIVE" => 'Y',
                        "EXTERNAL_ID" => $city->id,
                        "NAME" => $city->name,
                        'PROPERTY_VALUES' => array(
                            'COUNTRY' => $this->geo[$country]['ID']
                        )
                    );
                    if ($cityId = $this->el->Add($arFields)) {
                        $arFields['ID'] = $cityId;
                        $this->geo[$country][$city->id] = $arFields;
                        $this->geo[$country][$city->name] = &$this->geo[$country][$city->id];
                    } else {
                        $this->log('FATAL GEO CITY: dont find city', $this->geo[$country]);
                        $this->showMessage();
                        die ();
                    }
                }
            }
        }
    }
    public function loadCategories()
    {
        $rsResult = \CIBlockSection::GetList(array("SORT" => "ASC"), array("IBLOCK_ID" => 18), false, $arSelect = array('ID', 'IBLOCK_ID', "UF_*"));
        $this->categories = array();
        while ($arSection = $rsResult -> GetNext()) {
            if ($arSection['UF_ID_EBASC']){
                if (!isset($categories[$arSection['UF_ID_EBASC']])){
                    $this->categories[$arSection['UF_ID_EBASC']] = array();
                }
                $this->categories[$arSection['UF_ID_EBASC']][] = $arSection['ID'];
            }
        }
    }
    public function clearData(){ // чистим данные от ОЧЕНЬ умных людей
        $temp = array();
        foreach ($this->data->data->services->service as $keyService => $service) {
            $city = $this->geo[$service->country_id]['SITIES'][$service->city_id]['ID'];
            $clearName = $this->clearName($service->name);
            $clearAdress = $this->clearName($service->adress);
            if (isset($temp[$city][$clearName][$clearAdress])){
                foreach (array('phone', 'site', 'descr', 'mail') as $key){
                    if ($service->{$key} != $temp[$city][$clearName][$clearAdress]->{$key}) {
                        if (empty($service->{$key})){
                            //ничо не меняем
                        }elseif (empty($temp[$city][$clearName][$clearAdress]->{$key})){
                            $temp[$city][$clearName][$clearAdress]->{$key} = $service->{$key};
                        } else {
                            $service->{$key} .= ', ' . $temp[$city][$clearName][$clearAdress]->{$key};
                        }
                    }
                }
                if (isset($temp[$city][$clearName][$clearAdress]->codename->code->id)){
                    $temp[$city][$clearName][$clearAdress]->codename->code = array($temp[$city][$clearName][$clearAdress]->codename->code);
                }
                foreach ($service->codename->code as $item){
                    $temp[$city][$clearName][$clearAdress]->codename->code[]=$item;
                }
                unset($this->data->data->services->service[$keyService]);
            }else{
                $temp[$city][$clearName][$clearAdress]=&$this->data->data->services->service[$keyService];
            }

        }
    }
    public function clearName($name)
    {
        if ($name) {
            $name = preg_replace('/\&[^\;]+\;/isu', '', $name);
            $name = preg_replace('/\<[^\<\>]+\>/isu', '', $name);
            $name = preg_replace('/\n\r\t/isu', '', $name);
            $name = preg_replace('/[^а-яА-ЯёЁa-zA-Z0-9]/isu', '', $name);
        } else {
            $name = '';
        }
        return $name;
    }
    public function log($type, $message)
    {
        $this->messages[$type][] = $message;
        fwrite($this->log_file, $type . "\n");
        foreach ($message as $i){
            fwrite($this->log_file, print_r($i, 1) . "\n");
        }
        fflush ($this->log_file);
        //echo '<pre>'.$type.print_r($message,1).'</pre>';
    }
    public function importItem()
    {
        /**
         * дабы не дергать базу по каждой сервис компании, мы вызовем список
         */
        //$this->messages = array();
        $servicesDBName = array();
        $servicesDB = array();
        $activeDB = array();
        $rs = CIBlockElement::GetList(array(), array('IBLOCK_ID' => $this->targetIblock), false, false, array('ID', 'IBLOCK_ID', 'PREVIEW_TEXT', 'ACTIVE', 'NAME', 'PROPERTY_CITIES'));
        while ($ar = $rs->GetNext()) {
            $servicesDB[$ar['PROPERTY_CITIES_VALUE']][$this->clearName($ar['NAME'])][$this->clearName($ar['PREVIEW_TEXT'])] = $ar['ID'];
            $activeDB[$ar['ACTIVE']][$ar['ID']] = $ar['ID'];
            $servicesDBName[$ar['ID']] = $ar['NAME'];
        }
        foreach ($this->data->data->services->service as $service) {
            //$catsIds
            $categories = isset($service->codename->code->id) ? array($service->codename->code) : $service->codename->code;
            $categoriesItem = array();
            foreach ($categories as $category){
                if (isset($this->categories[$category->id])){
                    foreach ($this->categories[$category->id] as $i){
                        $categoriesItem[] = $i;
                    }
                }
            }

            $arFields = array(
                "IBLOCK_ID" => $this->targetIblock,
                "ACTIVE" => 'Y',
                "NAME" => $service->name,
                "PREVIEW_TEXT" => $service->adress,
                "DETAIL_TEXT" => $service->desc,
                "PROPERTY_VALUES" => array(
                    'CITIES' => isset($this->geo[$service->country_id]['SITIES'][$service->name]['ID'])
                        ?$this->geo[$service->country_id]['SITIES'][$service->name]['ID']
                        :$this->geo[$service->country_id]['SITIES'][$service->city_id]['ID'],
                    'PHONE' => $service->phone,
                    'SITE' => $service->site,
                    'CATEGORIES' => $categoriesItem,
                )
            );
            if (isset($this->citiesInDB[$arFields['PROPERTY_VALUES']['CITIES']])) {
/*
                if ($this->el->Update(
                    $arFields['PROPERTY_VALUES']['CITIES'],
                    array(
                        "ACTIVE" => 'Y',
                    )
                )) {
                    $this->log(
                        'activation',
                        array(
                            'Activation CityID:' . $arFields['PROPERTY_VALUES']['CITIES'],
                            $arFields
                        )
                    );
                } else {
                    $this->log(
                        'activationError',
                        array(
                            'ERROR: Activation City ID:' . $arFields['PROPERTY_VALUES']['CITIES'],
                            $arFields
                        )
                    );
                }*/
                unset($this->citiesInDB[$arFields['PROPERTY_VALUES']['CITIES']]);
            }
            $clearName = $this->clearName($arFields['NAME']);
            $clearAdress = $this->clearName($arFields['PREVIEW_TEXT']);
            /**
             * дорогой читатель.
             * я тут объяснюсь. мы можем вызывать по 1 элементу, как делал мой предшественник, и смотреть по результату.
             * НО... я не понимаю, зачем.
             * Потому, я напрягу память, в угоду сохранению нагрузки на базу, и вызову все сервисы (их не так уж и много) и обработаю по списку.
             */
            if (isset($servicesDB[$arFields['PROPERTY_VALUES']['CITIES']][$clearName][$clearAdress])){
                $arFields_ID = $servicesDB[$arFields['PROPERTY_VALUES']['CITIES']][$clearName][$clearAdress];
                unset ($servicesDB[$arFields['PROPERTY_VALUES']['CITIES']][$clearName][$clearAdress]);
                /**
                 * далее по блоку. дэвид блейн пил, и магия его была мягко говоря не очевидна
                 */
                $temp = array(
                    'Update ID:' . $arFields_ID . ' for ' . $arFields['NAME'] . '( ' . $arFields['PROPERTY_VALUES']['CITIES']. '|' . $clearName . '|' . $clearAdress . ' )',
                    $arFields
                );
                if (isset($arFields['PROPERTY_VALUES'])) {
                    CIBlockElement::SetPropertyValuesEx($arFields_ID, $arFields['IBLOCK_ID'], $arFields['PROPERTY_VALUES']);
                    unset($arFields['PROPERTY_VALUES']);
                }
                unset($arFields['IBLOCK_ID']);

                if ($this->el->Update($arFields_ID, $arFields)) {
                    $this->log('edit', $temp);
                    //$this->messages['edit'][] = $temp;
                } else {
                    $temp[0] = 'UPDATE ERROR:' . $this->el->LAST_ERROR . ' for ' . $arFields['NAME'];
                    $this->log('editError', $temp);
                }
            } else {
                if ($arFields_ID = $this->el->Add($arFields)) {

                    $this->log(
                        'add',
                        array(
                            'New ID:' . $arFields_ID . ' for ' . $arFields['NAME'] . '( ' . $arFields['PROPERTY_VALUES']['CITIES'] . '|' . $clearName. '|' . $clearAdress . ' )',
                            $arFields
                        )
                    );
                } else {
                    $this->log(
                        'addError',
                        array(
                            'ERROR:' . $this->el->LAST_ERROR . ' for ' . $arFields['NAME'],
                            $arFields
                        )
                    );
                }
            }
        }
        /**
         * мы молодцы. мы обработали все сервисные центры. теперь же, мы деактивируем лишнее!
         */
        $arFields = array(
            "ACTIVE" => 'N',
        );
            foreach ($servicesDB as $key=>$servicCityDB) {
            foreach ($servicCityDB as $key2=>$servicesDBID) {
                foreach ($servicesDBID as $key3=>$servicDB) {
                    if (isset($activeDB['Y'][$servicDB])) { // мы умные. деактивируем только то что активно!
                        if ($this->el->Update($servicDB, $arFields)) {
                            $this->log(
                                'deactivation',
                                array(
                                    'Deactivation ID:' . $servicDB . '( ' . $key . '|' . $key2 . '|' . $key3/*$this->clearName($servicesDBName[$servicDB])*/ . ' )',
                                    $arFields
                                )
                            );
                        } else {
                            $this->log(
                                'deactivationError',
                                array(
                                    'ERROR: Deactivation ID:' . $servicDB,
                                    $arFields
                                )
                            );
                        }
                    }
                }
            }
        }
        /*$arFields = array(
            "ACTIVE" => 'Y',
        );
        foreach ($this->citiesInDB as $cities) {
            if ($this->el->Update($cities, $arFields)) {
                $this->log(
                    'deactivation',
                    array(
                        'Deactivation CityID:' . $cities,
                        $arFields
                    )
                );
            } else {
                $this->log(
                    'deactivationError',
                    array(
                        'ERROR: Deactivation City ID:' . $cities,
                        $arFields
                    )
                );
            }
        }*/
    }
    public function connect($api_method, $post_params = array())
    {
        $url = $api_method['url'];
        $data = http_build_query($post_params);
        $opts = array(
            'http' => array (
                'method' => 'POST',
                'content' => $data,
                'header'=>
                    //"Content-type: application/x-www-form-urlencoded\r\n"
                    "Content-type: text/html; charset=utf8\r\n"
                    . "Authorization: " . $api_method['tokin'] . "\r\n"
                    . "Content-Length: " . strlen($data) . "\r\n",
            )
        );
        $ctx = stream_context_create($opts);
        $this->data = json_decode(file_get_contents($url,false, $ctx));
    }
}