public function actionSubcats() { $module = $this->getModule('portfolio'); $images = PortfolioImage::model()->findAll(['order' => 't.id ASC']); foreach ($images as $image) { //echo $image->title . '<br />'; $category = new PortfolioCategory(); $category->parent_id = $image->item_id; $category->title = $image->title != '' ? $image->title : $image->id; $category->status = $image->status; $category->sort = $image->sort; $category->image = $image->image; $alias = \yupe\helpers\YText::translit($category->title); //echo $alias . '<br />'; //var_dump($v); if (PortfolioCategory::model()->findByAttributes(array('alias' => $alias)) !== null) { //echo "repeat<br />"; $alias = $alias . '-' . mt_rand(10000, 99999); } $category->alias = $alias; //echo $category->alias . '<br />'; //echo '<hr>'; if ($category->save()) { copy(Yii::app()->uploadManager->getBasePath() . DIRECTORY_SEPARATOR . $module->getImagesUploadPath() . DIRECTORY_SEPARATOR . $image->image, Yii::app()->uploadManager->getBasePath() . DIRECTORY_SEPARATOR . $module->getCategoriesUploadPath() . DIRECTORY_SEPARATOR . $category->image); echo $image->id . ' - OK!<br />'; } else { var_dump($category->getErrors()); echo '<hr>'; } } }
public function generateAlias() { $alias = \yupe\helpers\YText::translit($this->getOwner()->{$this->titleAttribute}); if ($this->findByAlias($alias) !== null) { $alias = $alias . '-' . mt_rand(10000, 99999); } $this->getOwner()->{$this->aliasAttribute} = $alias; }
/** * @return bool */ protected function uploadFile() { if (!$this->uploadedFile) { return false; } $name = $this->uploadedFile->name; $extension = '.' . $this->uploadedFile->extensionName; // сгенерировать имя файла и сохранить его, // если не включено переименование, то все равно имя переводится в транслит, чтобы не было проблем $fileName = $this->rename ? md5(time() . uniqid() . $name) . $extension : YText::translit(str_ireplace($extension, '', $name)) . '_' . time() . $extension; if (!$this->uploadedFile->saveAs($this->uploadPath . $fileName)) { Yii::app()->ajax->raw(['error' => Yii::t('YupeModule.yupe', 'There is an error when downloading!')]); } $this->fileLink = Yii::app()->getBaseUrl() . $this->webPath . $fileName; $this->fileName = $name; return true; }
public static function getTranslatedName($word) { return YText::translit($word); }
/** * @return null|Product * @throws CDbException */ public function copy() { $transaction = Yii::app()->getDb()->beginTransaction(); $model = new Product(); try { $model->setAttributes($this->getAttributes()); $model->slug = null; $similarNamesCount = Yii::app()->getDb()->createCommand()->select('count(*)')->from($this->tableName())->where("name like :name", [':name' => $this->name . ' [%]'])->queryScalar(); $model->name = $this->name . ' [' . ($similarNamesCount + 1) . ']'; $model->slug = \yupe\helpers\YText::translit($model->name); $model->image = $this->image; $attributes = $model->attributes; $typeAttributes = $this->getTypesAttributesValues(); $variantAttributes = $categoriesIds = []; if ($variants = $this->variants) { foreach ($variants as $variant) { $variantAttributes[] = $variant->getAttributes(['attribute_id', 'attribute_value', 'amount', 'type', 'sku']); } } if ($categories = $this->categories) { foreach ($categories as $category) { $categoriesIds[] = $category->id; } } if (!$model->saveData($attributes, $typeAttributes, $variantAttributes, $categoriesIds)) { throw new CDbException('Error copy product!'); } $transaction->commit(); return $model; } catch (Exception $e) { $transaction->rollback(); } return null; }
public function actionCat() { $db = Yii::app()->db; Yii::app()->setImport(['application.modules.store.models.*']); //Создаем категории $cat1 = $db->createCommand("SELECT * FROM category_promItem c WHERE c.id_parent=0")->queryAll(); foreach ($cat1 as $c1) { $slug = \yupe\helpers\YText::translit($c1['name_rus']) . $c1['id']; $StoreCategory1 = StoreCategory::model()->findByAttributes(['slug' => $slug]); if (empty($StoreCategory1)) { $StoreCategory1 = new StoreCategory(); $StoreCategory1->name = $c1['name_rus']; $StoreCategory1->slug = $slug; $StoreCategory1->parent_id = 1; $StoreCategory1->save(); } $cat2 = $db->createCommand("SELECT * FROM category_promItem c WHERE c.id_parent=" . $c1['id'])->queryAll(); foreach ($cat2 as $c2) { $slug = \yupe\helpers\YText::translit($c2['name_rus']) . $c2['id']; $StoreCategory2 = StoreCategory::model()->findByAttributes(['slug' => $slug]); if (empty($StoreCategory2)) { $StoreCategory2 = new StoreCategory(); $StoreCategory2->name = $c2['name_rus']; $StoreCategory2->slug = $slug; $StoreCategory2->parent_id = $StoreCategory1->id; $StoreCategory2->save(); } $cat3 = $db->createCommand("SELECT * FROM category_promItem c WHERE c.id_parent=" . $c2['id'])->queryAll(); foreach ($cat3 as $c3) { $slug = \yupe\helpers\YText::translit($c3['name_rus']) . $c3['id']; $StoreCategory3 = StoreCategory::model()->findByAttributes(['slug' => $slug]); if (empty($StoreCategory3)) { $StoreCategory3 = new StoreCategory(); $StoreCategory3->name = $c3['name_rus']; $StoreCategory3->slug = $slug; $StoreCategory3->parent_id = $StoreCategory2->id; $StoreCategory3->save(); $cat4 = $db->createCommand("SELECT * FROM category_promItem c WHERE c.id_parent=" . $c3['id'])->queryAll(); foreach ($cat4 as $c4) { $slug = \yupe\helpers\YText::translit($c4['name_rus']) . $c4['id']; $StoreCategory4 = StoreCategory::model()->findByAttributes(['slug' => $slug]); if (empty($StoreCategory4)) { $StoreCategory4 = new StoreCategory(); $StoreCategory4->name = $c4['name_rus']; $StoreCategory4->slug = $slug; $StoreCategory4->parent_id = $StoreCategory3->id; $StoreCategory4->save(); } } } } } } //Создаем атрибуты /*$ids_item = []; $propertys = $db->createCommand("SELECT * FROM `property`")->queryAll(); foreach($propertys as $property) { $item = $db->createCommand("SELECT * FROM `items` WHERE id=".$property['id_item'])->queryRow(); $name = \yupe\helpers\YText::translit($item['name']).$property['id_category']; $Attribute = Attribute::model()->findByAttributes(['name' => $name]); if(empty($Attribute)) { $Attribute = new Attribute; $Attribute->name = $name; $Attribute->title = $item['name']; $Attribute->type = Attribute::TYPE_DROPDOWN; $Attribute->required = true; $Attribute->save(); $values = explode('|', $property['array_value']); foreach($values as $value) { $AttributeOption = new AttributeOption; $AttributeOption->attribute_id = $Attribute->id; $AttributeOption->value = $value; $AttributeOption->save(); } } $ids_item[$property['id']] = $Attribute->id; } //Создаем типы $cats = $db->createCommand("SELECT c1.* FROM category c1 LEFT JOIN category c2 ON c1.id=c2.id_parent WHERE c2.id IS NULL GROUP BY c1.name_rus")->queryAll(); foreach($cats as $cat) { $Type = new Type; $Type->name = $cat['name_rus']; $Type->save(); $props = $db->createCommand("SELECT * FROM `property` WHERE id_category=".$cat['id'])->queryAll(); foreach($props as $prop) { $TypeAttribute = new TypeAttribute; $TypeAttribute->type_id = $Type->id; $TypeAttribute->attribute_id = $ids_item[$prop['id']]; $TypeAttribute->save(); } for($i=2;$i<9;++$i) { $TypeAttribute = new TypeAttribute; $TypeAttribute->type_id = $Type->id; $TypeAttribute->attribute_id = $i; $TypeAttribute->save(); } } echo "\n";*/ }
public function actionIndex() { exit; // 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 getmicrotime() { list($usec, $sec) = explode(" ", microtime()); return (double) $usec + (double) $sec; } function logParse($message) { Yii::log($message, CLogger::LEVEL_TRACE, 'parse'); Yii::getLogger()->flush(true); } logParse("Begin"); $begin = getmicrotime(); $regexpArray = array('p' => '~^p\\..+~iU', 'pl' => '~^pl\\..+~iU', 'plx' => '~^plx\\..+~iU'); $titlesArray = array('p' => '', 'pl' => 'Плитка из камня', 'plx' => 'Плитка из камня с подсветкой'); $parsePath = Yii::app()->uploadManager->getBasePath() . DIRECTORY_SEPARATOR . $this->module->uploadPath . DIRECTORY_SEPARATOR . 'parse_tile'; $seriesList = glob($parsePath . DIRECTORY_SEPARATOR . '*', GLOB_BRACE | GLOB_ONLYDIR); $stones = array(); $imagesFiles = array(); // Обработка серий foreach ($seriesList as $skey => $seriesPath) { //if($skey > 1) break; $seriesAlias = basename($seriesPath); if ($seriesAlias == '.' || $seriesAlias == '..') { continue; } $series = Series::model()->findByAlias($seriesAlias); if (is_null($series)) { logParse("Серия " . $seriesAlias . " не найдена"); echo "Серия " . $seriesAlias . " не найдена<br />"; exit; } echo '<h1>' . $series->title . '</h1>'; logParse("Series " . $series->title); $stonesList = glob($seriesPath . DIRECTORY_SEPARATOR . '*', GLOB_BRACE | GLOB_ONLYDIR); $stonesCounter = 0; $stoneImagesCounter = 0; $sort = 0; foreach ($stonesList as $stonePath) { $stoneTitle = basename($stonePath); if ($stoneTitle == '.' || $stoneTitle == '..') { continue; } //echo '<h3>' . $stoneTitle . '</h3>'; $stonesCounter++; $sort += 100; $stone = new Stone(); $stone->type_id = 2; $stone->series_id = $series->id; $stone->title = $stoneTitle; $stone->metatitle = $stone->keywords = $stone->description = $stone->title; // Генерация алиаса $alias = \yupe\helpers\YText::translit($stone->title) . '-tile'; if ($stone->findByAlias($alias) !== null) { $alias = $alias . '-' . mt_rand(10000, 99999); } $stone->alias = $alias; $stone->sort = $sort; $imagesList = array(); foreach ($regexpArray as $key => $regexp) { foreach (CFileHelper::findFiles($stonePath) as $file) { //echo $file . '<br />'; if (preg_match($regexp, basename($file))) { $imagesList[$key] = $file; } } } $stoneImages = array(); foreach ($imagesList as $key => $item) { $itemName = basename($item); $newName = getNewFileName($item); $imagesFiles[] = array('fullPath' => $item, 'name' => $itemName, 'newName' => $newName); if (preg_match($regexpArray['p'], $itemName)) { $stone->image = $newName; //echo $itemName . '<br />'; } else { $image = new StoneImage(); $image->title = $titlesArray[$key]; $image->image = $newName; $stoneImages[] = $image; } //echo $itemName . '<br />'; $stoneImagesCounter++; } $stone->images = $stoneImages; $stones[] = $stone; } echo 'Камней: ' . $stonesCounter . '<br />'; echo 'Изображений: ' . $stoneImagesCounter . '<br />'; echo '<hr>'; } // Сохраняем камни и изображения в БД foreach ($stones as $stone) { logParse($stone->title); if ($stone->save(false)) { $imagesCounter = 0; foreach ($stone->images as $image) { $imagesCounter += 100; $image->item_id = $stone->id; $image->sort = $imagesCounter; if (!$image->save(false)) { logParse($image->image . ' - error'); echo $image->image . ' - error<br />'; } } logParse('success'); } else { logParse('error'); //echo $stone->title . ' - error<br />'; //var_dump($stone->getErrors()); } } // Копируем изображения foreach ($imagesFiles as $image) { copy($image['fullPath'], Yii::app()->uploadManager->getBasePath() . DIRECTORY_SEPARATOR . $this->module->getStonesUploadPath() . DIRECTORY_SEPARATOR . $image['newName']); } $end = getmicrotime(); $time = $end - $begin; echo "Время выполнения скрипта: " . $time . "с."; logParse("Время выполнения скрипта: " . $time . "с."); echo '<hr>'; }
/** * */ public function actionTransliterate() { $data = Yii::app()->getRequest()->getParam('data') ?: Yii::app()->getRequest()->getPost('data'); echo \yupe\helpers\YText::translit($data); }
public function run($args) { $max_id = isset($args[0]) ? $args[0] : 0; $root = dirname(dirname(__DIR__)); $parceBase = 'tiu_last'; $log_tiu = '/tmp/importTiu.log'; $log = '/tmp/importTiuSpec.log'; if (!file_exists($root . $log)) { copy($root . $log_tiu, $root . $log); file_put_contents($root . $log, 0); } $k = file_get_contents($root . $log); $db = \Yii::app()->db; if ($max_id == 0) { $max_id = $db->createCommand()->select('MAX(id)')->from($parceBase . '.product')->queryScalar(); } // рестарт if ($k == 0) { // предел - последний загруженный продукт $max_id = file_get_contents($root . $log_tiu); // все чистим echo "Clear tables ... \n"; $this->clear(); $k = 1; file_put_contents($root . $log, $k); } // импорт характеристик продуктов echo "Import product specifications ... \n"; echo "Max ID {$max_id} \n"; for ($k; $k <= $max_id; $k++) { $db->setActive(true); $dump_product = $db->createCommand()->select('*')->from($parceBase . '.specification')->where('id_product =' . $k)->queryAll(); if ($dump_product) { // найдем загруженный продукт $product_id = $db->createCommand()->select('id')->from('site_store_product')->where('tiu_id = "' . $k . '"')->queryScalar(); if ($product_id !== FALSE) { foreach ($dump_product as $spec) { if (!empty($spec['name']) and !empty($spec['value'])) { $name = \yupe\helpers\YText::translit($spec['name']); if (in_array($name, $this->attr_name)) { // пропускаем постоянные continue; } $sql = "INSERT INTO `site_store_product_option` (`product_id`, `title`, `value`) \n VALUES ('" . $product_id . "',:name,:value)"; $command = $db->createCommand($sql); $command->bindParam(':name', $spec["name"], PDO::PARAM_STR); $command->bindParam(':value', $spec["value"], PDO::PARAM_STR); $sql = $db->quoteValue($sql); $command->execute(); } } } else { print_r(" Error: can`t find product for tiu_id = {$k} \n"); file_put_contents($root . $log, $k); continue; } } print_r($k . "\n"); file_put_contents($root . $log, $k); } //file_put_contents($root . $log, 'The END'); }
public function saveSpec($spec, $product_id, $category_id, $type_id) { $name = \yupe\helpers\YText::translit($spec['name']); if (!in_array($name, $this->attr_name)) { if ($category_id) { // добавим в характеристику id категории $name = $name . $category_id; } else { print_r(" Error: can`t find StoreCategory for {$spec['id_product']} \n"); return; } } $model = Attribute::model()->findByAttributes(['name' => $name]); if (!$model) { $model = new Attribute(); $model->group_id = 1; $model->name = $name; $model->title = $spec['name']; $model->type = Attribute::TYPE_DROPDOWN; if ($model->save()) { $option = new AttributeOption(); $option->attribute_id = $model->id; $option->position = 0; $option->value = $spec['value']; if (!$option->save()) { echo "\n"; echo "Error: save AttributeOption for {$name} \n"; echo "\n"; } $TypeAttribute = new TypeAttribute(); $TypeAttribute->type_id = $type_id; $TypeAttribute->attribute_id = $model->id; if (!$TypeAttribute->save()) { echo "\n"; echo "Error: save TypeAttribute for {$name} \n"; echo "\n"; } } else { echo "\n"; echo "Error: save Attribute for {$name} \n"; echo "\n"; return; } } else { $this->addOption($spec, $model); } // свяжем продукт со значением характеристики $option = AttributeOption::model()->findByAttributes(['attribute_id' => $model->id, 'value' => $spec['value']]); if ($option) { $id = $option->id; $name = $model->name; $command = \Yii::app()->db->createCommand("\n INSERT INTO `site_store_product_attribute_eav` (`product_id`, `attribute`, `value`) \n VALUES ({$product_id}, '{$name}', {$id})\n ")->execute(); } }