/**
  * Action для ajax-подгрузки блока фильтра объектов, соответсвующего типу недвижимости
  * 
  * @param integer $typeId
  * @throws CHttpException
  */
 public function actionGetFilter($typeId)
 {
     if (!Yii::app()->request->isAjaxRequest) {
         //throw new CHttpException(403, 'Invalid request');
     }
     $realtyType = RealtyType::model()->published()->with(['category' => ['with' => 'types:published']])->findByPK($typeId);
     if (is_null($realtyType)) {
         throw new CHttpException(404);
     }
     $model = new RealtyItem('user_search');
     $model->unsetAttributes();
     $model->attachEavSet($realtyType->eav_set_id);
     $model->type_id = $realtyType->id;
     $model->category_id = $realtyType->category_id;
     $this->renderPartial('catalog/filter/_ajax_advanced_filter', ['category' => $realtyType->category, 'type' => $realtyType, 'model' => $model], false, true);
     Yii::app()->end();
 }
 public function actionIndex()
 {
     exit;
     $prefix = $_GET['prefix'];
     // prepare logger to dump logs every time one comes in
     Yii::getLogger()->autoFlush = 1;
     Yii::getLogger()->autoDump = true;
     function getNewFileName($fileName)
     {
         $ext = pathinfo($fileName, PATHINFO_EXTENSION);
         $oldName = pathinfo($fileName, PATHINFO_FILENAME);
         return md5(uniqid($fileName)) . '.' . $ext;
     }
     function logParse($message)
     {
         Yii::log($message, CLogger::LEVEL_TRACE, 'parse');
         Yii::getLogger()->flush(true);
     }
     //logParse("Begin");
     $begin = getmicrotime();
     // Начало
     $parsePath = Yii::app()->uploadManager->getBasePath() . DIRECTORY_SEPARATOR . $this->module->uploadPath . DIRECTORY_SEPARATOR . 'parse';
     $csvFile = $parsePath . DIRECTORY_SEPARATOR . "realty_{$prefix}.csv";
     $csvData = file_get_contents($csvFile);
     $csvData = mb_convert_encoding($csvData, 'utf-8', 'windows-1251');
     $csvData = explode("\r\n", $csvData);
     //var_dump($csvData);
     $categoryId = 1;
     //$typeId = 1;
     $category = RealtyCategory::model()->findByPK($categoryId);
     //$type = RealtyType::model()->findByPK($typeId);
     if (empty($category)) {
         throw new CHttpException(403, 'Incorrect category');
     }
     $realtyItems = [];
     $currencies = ['р.' => 1, '$' => 2, '€' => 3];
     $itemsCounter = 0;
     $galleriesList = CHtml::listData(RealtyGallery::model()->findAll(), 'xls_id', 'id');
     foreach ($csvData as $key => $row) {
         //if($key >= 20)
         //    break;
         $fields = str_getcsv($row, ";", '"');
         //$fields = explode(";", $row);
         //var_dump($fields);
         // Номер
         $num = (int) $fields[0];
         $imgFolderNum = $fields[1];
         if (empty($num)) {
             continue;
         }
         // Сделка
         $contractField = $fields[3];
         switch ($contractField) {
             case 'Продажа':
                 $contract = self::CONTRACT_SALE;
                 break;
             case 'Аренда':
                 $contract = self::CONTRACT_RENT;
                 break;
             default:
                 $contract = self::CONTRACT_SALE;
                 break;
         }
         // Тип недвижимости
         $typeField = $fields[2];
         switch ($typeField) {
             case 'Квартира':
                 $typeId = $contract == self::CONTRACT_RENT ? 4 : 1;
                 break;
             case 'Новостройка':
                 $typeId = 2;
                 break;
             default:
                 $typeId = 1;
                 break;
         }
         $type = RealtyType::model()->findByPK($typeId);
         if (empty($type)) {
             throw new CHttpException(403, 'Incorrect realty type');
         }
         $itemsCounter += 100;
         $realtyItem = new RealtyItem();
         if ($imgFolderNum == '-') {
             $realtyItem->status = 0;
         }
         // Направление недвижимости и тип
         $realtyItem->category_id = $categoryId;
         $realtyItem->type_id = $typeId;
         $realtyItem->attachEavSet($type->eav_set_id);
         $realtyItem->sort = $itemsCounter;
         $realtyItem->xls_id = $num;
         // Тип сделки
         $realtyItem->contract = $contract;
         // Район
         $district = trim($fields[4]);
         /*
                     $districtVariant = EavVariant::model()->find([
            'condition' => 't.attribute_id = :attribute_id AND LOWER(t.title) LIKE :title',
            'params' => [':attribute_id' => 10, ':title' => mb_strtolower($district)]
                     ]);
         */
         if ($district != '') {
             $district = $district == 'З' ? 'Запад' : $district;
             $districtVariant = EavVariant::model()->findByAttributes(['attribute_id' => 10, 'title' => $district]);
             $realtyItem->district = $districtVariant !== null ? $districtVariant->id : null;
         }
         // Метро
         $metro = trim($fields[5]);
         if ($metro != '') {
             $metro = mb_substr($metro, 2, mb_strlen($metro, 'utf-8') - 1, 'utf-8');
             $metro = trim($metro);
             $metroVariant = EavVariant::model()->findByAttributes(['attribute_id' => 28, 'title' => $metro]);
             if ($metroVariant !== null) {
                 $metroList = [$metroVariant->id];
             } else {
                 $criteria = new CDbCriteria();
                 $criteria->condition = 'attribute_id = :attribute_id AND title LIKE :title';
                 $criteria->params = [':attribute_id' => 28, ':title' => $metro . ' (%'];
                 $metroVariants = EavVariant::model()->findAll($criteria);
                 $metroList = [];
                 foreach ($metroVariants as $m) {
                     $metroList[] = $m->id;
                 }
             }
             $realtyItem->metro = $metroList;
         }
         // Адрес
         $realtyItem->name = trim($fields[6]);
         $realtyItem->address = trim($fields[6]);
         $realtyItem->itemAddress = 'Москва, ' . $realtyItem->address;
         // Жилой комплекс
         $realtyItem->residential_complex = trim($fields[7]);
         // Общая площадь
         $realtyItem->total_area = str_replace(',', '.', trim($fields[8]));
         // Этаж
         $storey = trim($fields[9]);
         $storey = preg_replace('~[^\\d\\-]+~', '', $storey);
         $realtyItem->storey = explode('-', trim($storey));
         // Этажность
         $storeysNum = preg_replace('~[^\\d]+~', '', $fields[10]);
         $realtyItem->storeys_number = trim($storeysNum);
         // Цена
         $realtyItem->price_per_sq_m = (double) preg_replace('~[^\\d]+~', '', $fields[11]);
         $realtyItem->price = (double) preg_replace('~[^\\d]+~', '', $fields[12]);
         $currency = preg_replace('~[\\d ]+~', '', $fields[11]);
         $realtyItem->currency_id = key_exists($currency, $currencies) ? $currencies[$currency] : reset($currencies);
         // Пентхаус
         $realtyItem->penthouse = trim($fields[13]) != '' ? 1 : 0;
         // Кол-во комнат
         $realtyItem->rooms_number = (int) trim($fields[14]);
         // Отделка
         $realtyItem->decoration = trim($fields[15]) != '' ? 1 : 0;
         // Паркинг
         $parkingPlacesNum = trim($fields[16]) != '' ? (int) $fields[16] : 0;
         $realtyItem->parking_places_num = $parkingPlacesNum;
         $realtyItem->parking = $parkingPlacesNum > 0 ? 1 : 0;
         // Описание
         $realtyItem->full_text = trim($fields[17], '"');
         // Изображения
         if ($imgFolderNum != '') {
             $imagesPath = $parsePath . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . $imgFolderNum;
             if (file_exists($imagesPath)) {
                 $realtyItem->gallery_xls_id = $imgFolderNum;
                 if (key_exists($imgFolderNum, $galleriesList)) {
                     $realtyItem->gallery_id = $galleriesList[$imgFolderNum];
                 }
             }
         }
         $realtyItems[] = $realtyItem;
         /*
                     var_dump($realtyItem->lotnum);
                     var_dump($realtyItem->district);
                     echo '<hr>';
         *
         */
     }
     echo 'Объектов: ' . count($realtyItems) . '<br />';
     echo '<hr>';
     //exit();
     // Сохраняем объекты и изображения в БД
     foreach ($realtyItems as $realtyItem) {
         //logParse($realtyItem->title);
         if ($realtyItem->saveWithEavAttributes()) {
             // Сохраняем номер лота
             $realtyItem->lotnum = implode('', [$realtyItem->category->id, $realtyItem->id]);
             $realtyItem->update(['lotnum']);
             //logParse('success');
         } else {
             //logParse('error');
             echo $realtyItem->title . ' - error<br />';
             var_dump($realtyItem->getErrors());
         }
     }
     $end = getmicrotime();
     $time = $end - $begin;
     echo "Время выполнения скрипта: " . $time . "с.";
     //logParse("Время выполнения скрипта: " . $time . "с.");
     echo '<hr>';
 }