Пример #1
0
 function actionSave()
 {
     if ($_SERVER['REQUEST_METHOD'] != 'POST') {
         throw new MyException('Вы не туда попали.');
     }
     if (empty($_POST['title'])) {
         throw new MyException('Поле "Заголовок" - обязательное!');
     }
     if ($_FILES['img']['name']) {
         $types = array('image/gif', 'image/png', 'image/jpeg');
         $size = 10000000;
         if (!in_array($_FILES['img']['type'], $types)) {
             throw new MyException('Мы такие форматы не грузим.');
         }
         if ($_FILES['img']['size'] > $size) {
             throw new MyException('Слишком большой размер картинки.');
         }
         $image = file_get_contents($_FILES['img']['tmp_name']);
     }
     $obj = new ObjectModel();
     $obj->title = $_POST['title'];
     $obj->text = $_POST['text'];
     $obj->type = $_POST['type'];
     $obj->img = $image ? $image : null;
     $obj->insert();
     header("Location: http://work/objectForDB/");
     exit;
 }
Пример #2
0
 public function run()
 {
     $this->genButton = Html::a(Icon::show('edit') . Yii::t('app', 'Generate'), '#', ['class' => 'btn btn-success', 'id' => 'btn-generate']);
     $parent_id = $this->model->main_category_id;
     $owner_id = $this->model->id;
     $this->addButton = Html::a(Icon::show('plus') . Yii::t('app', 'Add'), Url::toRoute(['/shop/backend-product/edit', 'parent_id' => $parent_id, 'owner_id' => $owner_id, 'returnUrl' => \app\backend\components\Helper::getReturnUrl()]), ['class' => 'btn btn-success', 'id' => 'btn-add']);
     if (!empty($this->footer)) {
         $this->footer = Html::tag('div', $this->addButton . ' ' . $this->genButton, ['class' => 'widget-footer']);
     }
     $this->object = Object::getForClass(get_class($this->model));
     $rest_pg = (new Query())->select('id, name')->from(PropertyGroup::tableName())->where(['object_id' => $this->object->id])->orderBy('sort_order')->all();
     $this->property_groups_to_add = [];
     foreach ($rest_pg as $row) {
         $this->property_groups_to_add[$row['id']] = $row['name'];
     }
     $optionGenerate = Json::decode($this->model->option_generate);
     if (null === PropertyGroup::findOne($optionGenerate['group'])) {
         $this->model->option_generate = $optionGenerate = null;
     }
     $groupModel = null;
     if (isset($optionGenerate['group'])) {
         $groupModel = PropertyGroup::findOne($optionGenerate['group']);
         $properties = Property::getForGroupId($optionGenerate['group']);
     } else {
         $group_ids = array_keys($this->property_groups_to_add);
         $group_id = array_shift($group_ids);
         $groupModel = PropertyGroup::findOne($group_id);
         $properties = Property::getForGroupId($group_id);
     }
     if (is_null($groupModel)) {
         $groupModel = new PropertyGroup();
     }
     return $this->render($this->viewFile, ['model' => $this->model, 'form' => $this->form, 'groups' => $this->property_groups_to_add, 'groupModel' => $groupModel, 'properties' => $properties, 'optionGenerate' => $optionGenerate, 'footer' => $this->footer]);
 }
Пример #3
0
 public function actionExport($importModel)
 {
     /** @var ImportModel $model */
     $model = new ImportModel();
     $model->unserialize($importModel);
     if ($model->validate()) {
         /** @var Export $exportStatus */
         $exportStatus = Export::find()->where(['user_id' => $model->getUser(), 'object_id' => $model->object])->one();
         $exportStatus->status = Export::STATUS_PROCESS;
         $exportStatus->save();
         try {
             $object = Object::findById($model->object);
             if ($object === null) {
                 throw new Exception('Object not found');
             }
             $filename = $model->getFilename('Export');
             $import = \app\modules\data\components\Import::createInstance(['object' => $object, 'filename' => $filename, 'type' => $model->type]);
             $import->processExport($model->fields, $model->conditions);
             $exportStatus->filename = $filename;
             $exportStatus->status = Export::STATUS_COMPLETE;
             $exportStatus->save();
         } catch (\Exception $e) {
             $exportStatus->status = Export::STATUS_FAILED;
             $exportStatus->save();
             echo $e->getMessage();
             throw $e;
         }
     } else {
         echo 'Model is not valid';
         throw new Exception('Model is not valid');
     }
 }
Пример #4
0
 function __construct($filename)
 {
     if (is_file($filename)) {
         $this->filename = $filename;
         $xml = new \XMLReader();
         if (false !== $xml->open($filename)) {
             $this->xml = $xml;
             $rootCategory = Category::findOne(['parent_id' => 0]);
             if (empty($rootCategory)) {
                 if (null === ($rootCategory = Category::createEmptyCategory(0, null, 'Каталог'))) {
                     $this->xml->close();
                     $this->xml = null;
                 }
                 $this->rootCategoryCache = $rootCategory->id;
             } else {
                 $this->rootCategoryCache = $rootCategory->id;
             }
             if (empty(static::$propertiesCache)) {
                 static::$propertiesCache = array_reduce(CommercemlGuid::find([['>', 'model_id', 0], ['type' => 'PROPERTY']])->all(), function ($result, $item) {
                     $result[$item['guid']] = $item->property;
                     return $result;
                 }, []);
             }
             $this->objectProduct = Object::getForClass(Product::className());
         }
     }
 }
 public function run()
 {
     $query = Category::find();
     $query->andWhere([Category::tableName() . '.active' => 1]);
     if ($this->root_category_id !== null) {
         $query->andWhere([Category::tableName() . '.parent_id' => $this->root_category_id]);
     }
     if ($this->category_group_id !== null) {
         $query->andWhere([Category::tableName() . '.category_group_id' => $this->category_group_id]);
     }
     $query->groupBy(Category::tableName() . ".id");
     $query->orderBy($this->sort);
     if ($this->limit !== null) {
         $query->limit($this->limit);
     }
     $object = Object::getForClass(Category::className());
     \app\properties\PropertiesHelper::appendPropertiesFilters($object, $query, $this->values_by_property_id, []);
     $sql = $query->createCommand()->getRawSql();
     $cacheKey = "FilteredCategoriesWidget:" . md5($sql);
     $result = Yii::$app->cache->get($cacheKey);
     if ($result === false) {
         $categories = Category::findBySql($sql)->all();
         $result = $this->render($this->viewFile, ['categories' => $categories]);
         Yii::$app->cache->set($cacheKey, $result, 86400, new \yii\caching\TagDependency(['tags' => ActiveRecordHelper::getCommonTag(Category::tableName())]));
     }
     return $result;
 }
Пример #6
0
 public function actionIndex($category_id = null)
 {
     $searchModel = new Category();
     $searchModel->active = 1;
     $params = Yii::$app->request->get();
     $dataProvider = $searchModel->search($params);
     $selectedCategory = null;
     if ($category_id !== null) {
         $selectedCategory = Category::findById($category_id);
     }
     if ($selectedCategory !== null) {
         if (Yii::$app->request->isPost === true) {
             $newProperty = isset($_GET['add_property_id']) ? Property::findById($_GET['add_property_id']) : null;
             if ($newProperty !== null) {
                 $filterSet = new FilterSets();
                 $filterSet->category_id = $selectedCategory->id;
                 $filterSet->property_id = $newProperty->id;
                 $filterSet->sort_order = 65535;
                 $filterSet->save();
             }
         }
     }
     $groups = PropertyGroup::getForObjectId(Object::getForClass(Product::className())->id, false);
     $propertiesDropdownItems = [];
     foreach ($groups as $group) {
         $item = ['label' => $group->name, 'url' => '#', 'items' => []];
         $properties = Property::getForGroupId($group->id);
         foreach ($properties as $prop) {
             $item['items'][] = ['label' => $prop->name, 'url' => '?category_id=' . $category_id . '&add_property_id=' . $prop->id, 'linkOptions' => ['class' => 'add-property-to-filter-set', 'data-property-id' => $prop->id, 'data-action' => 'post']];
         }
         $propertiesDropdownItems[] = $item;
     }
     return $this->render('index', ['dataProvider' => $dataProvider, 'searchModel' => $searchModel, 'selectedCategory' => $selectedCategory, 'propertiesDropdownItems' => $propertiesDropdownItems]);
 }
 /**
  * @return string
  */
 public function actionPrint()
 {
     $this->layout = 'print';
     $products = ProductCompareHelper::getProductsList(true);
     $object = Object::getForClass(Product::className());
     return $this->render('print', ['error' => empty($products) || null === $object, 'message' => Yii::t('app', 'No products for comparing'), 'object' => $object, 'products' => $products]);
 }
 public function down()
 {
     $objects = \app\models\Object::find()->asArray()->all();
     foreach ($objects as $object) {
         $this->dropColumn($object['eav_table_name'], 'property_group_id');
     }
 }
Пример #9
0
 /**
  * Delete relations
  * @return bool
  */
 public function cleanUpRelations()
 {
     if (!is_subclass_of($this->owner, '\\yii\\db\\ActiveRecord')) {
         return false;
     }
     if (isset($this->owner->is_deleted) && 0 === intval($this->owner->is_deleted)) {
         return false;
     }
     if (null === ($object = Object::getForClass($this->owner->className()))) {
         return false;
     }
     $whereDelete = ['object_id' => $object->id, 'object_model_id' => $this->owner->id];
     ObjectPropertyGroup::deleteAll($whereDelete);
     ObjectStaticValues::deleteAll($whereDelete);
     Image::deleteAll($whereDelete);
     ViewObject::deleteAll($whereDelete);
     try {
         Yii::$app->db->createCommand()->delete($object->categories_table_name, ['object_model_id' => $this->owner->id])->execute();
         Yii::$app->db->createCommand()->delete($object->column_properties_table_name, ['object_model_id' => $this->owner->id])->execute();
         Yii::$app->db->createCommand()->delete($object->eav_table_name, ['object_model_id' => $this->owner->id])->execute();
     } catch (Exception $e) {
         // do nothing
     }
     return true;
 }
 public function actionEdit($id = null)
 {
     $model = new PrefilteredPages();
     $model->loadDefaultValues();
     if ($id !== null) {
         $model = PrefilteredPages::findOne($id);
     }
     $static_values_properties = [];
     $property_groups_ids_for_object = (new Query())->select('id')->from(PropertyGroup::tableName())->where(['object_id' => Object::getForClass(Product::className())->id])->column();
     $properties = Property::find()->andWhere(['in', 'property_group_id', $property_groups_ids_for_object])->all();
     foreach ($properties as $prop) {
         /** @var Property $prop */
         $static_values_properties[$prop->id] = ['property' => $prop, 'static_values_select' => PropertyStaticValues::getSelectForPropertyId($prop->id), 'has_static_values' => $prop->has_static_values === 1];
     }
     $post = \Yii::$app->request->post();
     if ($model->load($post) && $model->validate()) {
         $save_result = $model->save();
         if ($save_result) {
             Yii::$app->session->setFlash('info', Yii::t('app', 'Object saved'));
             $returnUrl = Yii::$app->request->get('returnUrl', ['index', 'id' => $model->id]);
             switch (Yii::$app->request->post('action', 'save')) {
                 case 'next':
                     return $this->redirect(['edit', 'returnUrl' => $returnUrl]);
                 case 'back':
                     return $this->redirect($returnUrl);
                 default:
                     return $this->redirect(Url::toRoute(['edit', 'id' => $model->id, 'returnUrl' => $returnUrl]));
             }
             //return $this->redirect(['/backend/prefiltered-pages/edit', 'id' => $model->id]);
         } else {
             \Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot update data'));
         }
     }
     return $this->render('prefiltered-page-form', ['model' => $model, 'static_values_properties' => $static_values_properties]);
 }
Пример #11
0
 public function getData()
 {
     $objectClass = Object::findById($this->objectId)->object_class;
     $object = new $objectClass();
     $this->data = $object->attributeLabels();
     return parent::getData();
 }
Пример #12
0
 protected function getLinks()
 {
     if (!is_null($this->frontendLink) || !is_null($this->backendLink)) {
         return true;
     }
     /** @var Image $image */
     $image = Image::findById($this->img_id);
     if (is_null($image) || is_null($object = Object::findById($image->object_id))) {
         return false;
     }
     /** @var \app\models\Object $object */
     switch ($object->object_class) {
         case Page::className():
             $this->getPageLinks($image->object_model_id);
             break;
         case Category::className():
             $this->getCategoryLinks($image->object_model_id);
             break;
         case Product::className():
             $this->getProductLinks($image->object_model_id);
             break;
         default:
             return false;
     }
     return true;
 }
 /**
  * Unified action for import and export
  * @param $id
  * @param $importMode
  * @return string|\yii\web\Response
  * @throws ErrorException
  */
 private function unifiedAction($id, $importMode)
 {
     $object = Object::findById($id);
     /* @var $className \app\modules\data\models\Import */
     $className = $importMode ? 'app\\modules\\data\\models\\Import' : 'app\\modules\\data\\models\\Export';
     if ($object !== null) {
         $model = new ImportModel(['object' => $id]);
         $fields = \app\modules\data\components\Import::getFields($model->object);
         if (\Yii::$app->request->isPost) {
             if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
                 $import = $className::find()->where(['user_id' => Yii::$app->user->id, 'object_id' => $id])->one();
                 if ($import === null) {
                     $import = new $className(['user_id' => Yii::$app->user->id, 'object_id' => $id]);
                 }
                 $import->filename = null;
                 if ($importMode === true) {
                     $file = UploadedFile::getInstance($model, 'file');
                     $model->type = $file->extension;
                     $filename = $model->getFilename('Import');
                     $import->filename = $filename;
                     $fullFilename = Yii::$app->getModule('data')->importDir . '/' . $filename;
                     if ($file->saveAs($fullFilename) === false) {
                         throw new ErrorException("Unable to save file");
                     }
                 }
                 $import->status = $className::STATUS_PROCESS;
                 $task_options = Yii::$app->request->post('Task', []);
                 if ($import->save()) {
                     BackgroundTasks::addTask(['name' => $importMode ? 'import' : 'export', 'description' => ($importMode ? 'import' : 'export') . " {$model->object}", 'action' => 'data/file/' . ($importMode ? 'import' : 'export'), 'params' => $model->serialize(), 'init_event' => $importMode ? 'import' : 'export'], ['create_notification' => isset($task_options['create_notification']) && 1 == $task_options['create_notification'] ? true : false]);
                     \Yii::$app->session->setFlash('info', \Yii::t('app', 'Task is queued. Come back later.'));
                 } else {
                     \Yii::$app->session->setFlash('error', \Yii::t('app', 'Import Error'));
                 }
                 return $this->redirect(['/data/file']);
             }
         }
         $availablePropertyGroups = [];
         /** @var \app\modules\shop\models\Product $exampleModel - product for example */
         $exampleModel = new $object->object_class();
         if ($exampleModel->hasMethod('getPropertyGroups')) {
             $availablePropertyGroups = $exampleModel->getPropertyGroups(false, true);
         }
         \Yii::$app->session->setFlash('info', \Yii::t('app', 'Specify fields to import and select the file'));
         $fields['additionalFields'] = [];
         if ($exampleModel instanceof ExportableInterface) {
             $fields['additionalFields'] = $exampleModel::exportableAdditionalFields();
         }
         if ($model->type === null) {
             $model->type = Yii::$app->modules['data']->defaultType;
         }
         return $this->render('import-export', ['model' => $model, 'object' => $object, 'fields' => $fields, 'availablePropertyGroups' => $availablePropertyGroups, 'importMode' => $importMode]);
     } else {
         \Yii::$app->session->setFlash('error', \Yii::t('app', 'Object not found'));
         return $this->redirect(['/data/file']);
     }
 }
 public function down()
 {
     $this->dropTable('{{%special_price_list_type}}');
     $this->dropTable('{{%special_price_object}}');
     $this->dropColumn('{{%special_price_list}}', 'type_id');
     $this->addColumn('{{%special_price_list}}', 'type', "ENUM('core', 'discount', 'delivery', 'project') DEFAULT 'project'");
     $this->update('{{%special_price_list}}', ['type' => 'core'], ['class' => 'app\\modules\\shop\\models\\Currency', 'object_id' => Object::getForClass(Product::className())->id]);
     $this->update('{{%special_price_list}}', ['type' => 'discount'], ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => Object::getForClass(Product::className())->id]);
     $this->delete('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => Object::getForClass(Order::className())->id]);
 }
Пример #15
0
 public function getBindedAddons()
 {
     $object_id = Object::getForClass($this->className())->id;
     return $this->hasMany(Addon::className(), ['id' => 'addon_id'])->viaTable('{{%addon_bindings}}', ['object_model_id' => 'id'], function ($query) use($object_id) {
         /** @var \yii\db\Query $query */
         $query->andWhere(['appliance_object_id' => $object_id]);
         $query->orderBy(['sort_order' => SORT_ASC]);
         return $query;
     })->innerJoin('{{%addon_bindings}}', 'addon_id=addon.id AND appliance_object_id=:aoid AND object_model_id=:oid', [':aoid' => $object_id, ':oid' => $this->id])->orderBy(['addon_bindings.sort_order' => SORT_ASC]);
 }
Пример #16
0
 public function run()
 {
     $object = app\models\Object::getForClass($this->model->className());
     /** @var \app\modules\shop\models\AddonCategory $addonCategories */
     $addonCategories = app\components\Helper::getModelMap(AddonCategory::className(), 'id', 'name');
     /** @var app\modules\shop\models\Addon $bindedAddons */
     $bindedAddons = $this->model->bindedAddons;
     $addAddonModel = new AddAddonModel();
     return $this->render('addons-widget', ['object' => $object, 'addonCategories' => $addonCategories, 'bindedAddons' => $bindedAddons, 'model' => $this->model, 'form' => $this->form, 'addAddonModel' => $addAddonModel]);
 }
Пример #17
0
 public function getObject()
 {
     if ($this->object === null) {
         $this->object = Object::getForClass(get_class($this->owner));
         if ($this->object === null) {
             throw new \Exception("Can't find Object row for " . get_class($this->owner));
         }
     }
     return $this->object;
 }
 public function up()
 {
     $submissionObject = Object::getForClass(\app\models\Submission::className());
     /** @var PropertyHandler $propertyHandler */
     $propertyHandler = PropertyHandler::findOne(['name' => 'Text']);
     $this->addColumn(Review::tableName(), 'submission_id', 'INT UNSIGNED NOT NULL');
     $form = new \app\models\Form();
     $form->name = 'Review form';
     $form->email_notification_addresses = '';
     $form->email_notification_view = '@app/modules/review/views/review-email-template.php';
     $form->save(false, ['name', 'email_notification_addresses', 'email_notification_view']);
     $propertyGroup = new PropertyGroup();
     $propertyGroup->attributes = ['object_id' => $form->object->id, 'name' => 'Review form additional properties', 'hidden_group_title' => 1];
     $propertyGroup->save(true, ['object_id', 'name', 'hidden_group_title']);
     $nameProperty = new Property();
     $nameProperty->attributes = ['property_group_id' => $propertyGroup->id, 'name' => 'Name', 'key' => 'name', 'property_handler_id' => $propertyHandler->id, 'handler_additional_params' => '{}', 'is_eav' => 1];
     $nameProperty->save(true, ['property_group_id', 'name', 'key', 'property_handler_id', 'is_eav', 'handler_additional_params']);
     $phoneProperty = new Property();
     $phoneProperty->attributes = ['property_group_id' => $propertyGroup->id, 'name' => 'Phone', 'key' => 'phone', 'property_handler_id' => $propertyHandler->id, 'handler_additional_params' => '{}', 'is_eav' => 1];
     $phoneProperty->save(true, ['property_group_id', 'name', 'key', 'property_handler_id', 'is_eav', 'handler_additional_params']);
     $objectPropertyGroup = new ObjectPropertyGroup();
     $objectPropertyGroup->attributes = ['object_id' => $form->object->id, 'object_model_id' => $form->id, 'property_group_id' => $propertyGroup->id];
     $objectPropertyGroup->save(true, ['object_id', 'object_model_id', 'property_group_id']);
     $reviews = Review::find()->all();
     foreach ($reviews as $review) {
         $submission = new \app\models\Submission();
         $submission->form_id = $form->id;
         $submission->processed_by_user_id = $review->author_user_id;
         $submission->date_received = $review->date_submitted;
         $submission->save(false, ['form_id', 'processed_by_user_id', 'date_received']);
         $review->submission_id = $this->db->lastInsertID;
         $review->save(true, ['submission_id']);
         $this->insert(ObjectPropertyGroup::tableName(), ['object_id' => $submissionObject->id, 'object_model_id' => $submission->id, 'property_group_id' => $propertyGroup->id]);
         $this->insert($submissionObject->eav_table_name, ['object_model_id' => $submission->id, 'property_group_id' => $propertyGroup->id, 'key' => $nameProperty->key, 'value' => $review->author_name]);
         $this->insert($submissionObject->eav_table_name, ['object_model_id' => $submission->id, 'property_group_id' => $propertyGroup->id, 'key' => $phoneProperty->key, 'value' => $review->author_phone]);
     }
     $this->dropColumn(Review::tableName(), 'date_submitted');
     $this->dropColumn(Review::tableName(), 'author_user_id');
     $this->dropColumn(Review::tableName(), 'author_name');
     $this->dropColumn(Review::tableName(), 'author_phone');
     $this->dropColumn(Review::tableName(), 'rate');
     $this->renameColumn(Review::tableName(), 'text', 'review_text');
     $this->alterColumn(Review::tableName(), 'rating_id', 'CHAR(32)');
     $this->update(BackendMenu::tableName(), ['route' => 'review/backend-rating/index'], ['route' => 'backend/rating/index']);
     $this->update(BackendMenu::tableName(), ['route' => 'review/backend-review/index'], ['name' => 'Reviews']);
     $this->delete(BackendMenu::tableName(), ['route' => ['review/backend/products', 'review/backend/pages']]);
     $this->alterColumn(RatingValues::tableName(), 'rating_id', 'CHAR(32) NOT NULL');
     $this->alterColumn(RatingValues::tableName(), 'object_id', 'INT UNSIGNED NOT NULL');
     $this->alterColumn(RatingValues::tableName(), 'object_model_id', 'INT UNSIGNED NOT NULL');
     $this->alterColumn(RatingValues::tableName(), 'rating_item_id', 'INT UNSIGNED NOT NULL');
     $this->alterColumn(RatingValues::tableName(), 'user_id', 'INT UNSIGNED NOT NULL');
     $this->createIndex('ix-rating_values-rating_id', RatingValues::tableName(), 'rating_id');
     $this->createIndex('ix-rating_values-object_id-object_model_id', RatingValues::tableName(), ['object_id', 'object_model_id']);
     $this->createIndex('ix-rating_item-rating_group', RatingItem::tableName(), 'rating_group');
 }
Пример #19
0
 /**
  * @inheritdoc
  * @param int $id
  * @return int|mixed
  * @throws NotFoundHttpException
  */
 public function run($id)
 {
     /** @var Form|HasProperties $form */
     if (null === ($form = Form::findById($id))) {
         throw new NotFoundHttpException();
     }
     $post = Yii::$app->request->post();
     $form->abstractModel->setAttrubutesValues($post);
     /** @var AbstractModel|SpamCheckerBehavior $model */
     $model = $form->getAbstractModel();
     if (Yii::$app->request->isAjax && isset($post['ajax'])) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         return ActiveForm::validate($model);
     }
     /** @var \app\models\Object $object */
     $object = Object::getForClass(Form::className());
     $propGroups = ObjectPropertyGroup::find()->where(['and', 'object_id = :object', 'object_model_id = :id'], [':object' => $object->id, ':id' => $id])->asArray()->all();
     $propIds = ArrayHelper::getColumn($propGroups, 'property_group_id');
     // Spam checking
     $activeSpamChecker = SpamChecker::getActive();
     $data = [];
     $haveSpam = false;
     if ($activeSpamChecker !== null && !empty($activeSpamChecker->api_key)) {
         $data[$activeSpamChecker->name]['class'] = $activeSpamChecker->behavior;
         $data[$activeSpamChecker->name]['value']['key'] = $activeSpamChecker->api_key;
         $properties = Property::getForGroupId($propIds[0]);
         foreach ($properties as $prop) {
             if (!isset($activeSpamChecker->{$prop->interpret_as}) || empty($activeSpamChecker->{$prop->interpret_as})) {
                 continue;
             }
             $data[$activeSpamChecker->name]['value'][$activeSpamChecker->{$prop->interpret_as}] = is_array($post[$form->abstractModel->formName()][$prop->key]) ? implode(' ', $post[$form->abstractModel->formName()][$prop->key]) : $post[$form->abstractModel->formName()][$prop->key];
         }
         $model->attachBehavior('spamChecker', ['class' => SpamCheckerBehavior::className(), 'data' => $data]);
         $haveSpam = $model->isSpam();
     }
     $date = new \DateTime();
     /** @var Submission|HasProperties $submission */
     $submission = new Submission(['form_id' => $form->id, 'date_received' => $date->format('Y-m-d H:i:s'), 'ip' => Yii::$app->request->userIP, 'user_agent' => Yii::$app->request->userAgent, 'spam' => (int) $haveSpam]);
     if (false === Yii::$app->user->isGuest) {
         $submission->processed_by_user_id = Yii::$app->user->identity->getId();
     }
     if (!($form->abstractModel->validate() && $submission->save())) {
         return "0";
     }
     if (isset($post[$form->abstractModel->formName()])) {
         $data = ['AddPropetryGroup' => [$submission->formName() => array_keys($form->getPropertyGroups())], $submission->abstractModel->formName() => $post[$form->abstractModel->formName()]];
         if (isset($_FILES[$form->abstractModel->formName()])) {
             $_FILES[$submission->abstractModel->formName()] = $_FILES[$form->abstractModel->formName()];
         }
         $submission->saveProperties($data);
     }
     return $submission->id;
 }
 public function up()
 {
     //  return false;
     $this->addColumn('{{%special_price_list}}', 'handler', Schema::TYPE_STRING);
     $this->update('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler' => 'getCurrencyPriceProduct'], ['class' => 'app\\modules\\shop\\models\\Currency', 'object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Product::className())->id]);
     $this->update('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler' => 'getDiscountPriceProduct'], ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Product::className())->id]);
     $this->update('{{%special_price_list}}', ['class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler' => 'getDiscountPriceOrder'], ['class' => 'app\\modules\\shop\\models\\Discount', 'object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Order::className())->id]);
     $this->insert('{{%special_price_list}}', ['object_id' => \app\models\Object::getForClass(\app\modules\shop\models\Order::className())->id, 'class' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'active' => 1, 'sort_order' => 12, 'handler' => 'getDeliveryPriceOrder', 'type_id' => (new \yii\db\Query())->select('id')->from('{{%special_price_list_type}}')->where(['key' => 'delivery'])->scalar()]);
     $this->insert('{{%events}}', ['owner_class_name' => 'app\\modules\\shop\\ShopModule', 'event_name' => 'order_calculate', 'event_class_name' => 'app\\modules\\shop\\events\\OrderCalculateEvent', 'selector_prefix' => '', 'event_description' => '', 'documentation_link' => '']);
     $eventId = $this->db->lastInsertID;
     $this->insert('{{%event_handlers}}', ['event_id' => $eventId, 'sort_order' => 0, 'handler_class_name' => 'app\\modules\\shop\\helpers\\PriceHandlers', 'handler_function_name' => 'handleSaveDiscounts', 'is_active' => 1, 'non_deletable' => 0, 'triggering_type' => 'application_trigger']);
 }
 public function search($params)
 {
     /* @var $query \yii\db\ActiveQuery */
     $query = $this->baseModel->find();
     $table_inheritance_joined = false;
     $dataProvider = new ActiveDataProvider(['query' => &$query, 'pagination' => ['pageSize' => 10], 'sort' => ['defaultOrder' => ['id' => SORT_DESC]]]);
     if (!$this->load($params)) {
         return $dataProvider;
     }
     $object = Object::getForClass($this->baseModel->className());
     $baseModelTableName = $this->baseModel->tableName();
     $eavJoinsCount = 0;
     $osvJoinsCount = 0;
     foreach ($this->propertyGroups as $groupId => $properties) {
         foreach ($properties as $key => $propertyValue) {
             /** @var \app\properties\PropertyValue $propertyValue */
             $prop = Property::findById($propertyValue->property_id);
             if (empty($this->{$prop->key}) === true && $this->{$prop->key} !== '0') {
                 continue;
             }
             // determine property storage type and join needed table if needed
             if ($prop->is_column_type_stored) {
                 if ($table_inheritance_joined === false) {
                     $table_inheritance_joined = true;
                     $query->join('INNER JOIN', $object->column_properties_table_name . ' ti', 'ti.object_model_id = ' . $baseModelTableName . '.id');
                 }
                 if ($prop->value_type === 'STRING' && $prop->property_handler_id !== 3) {
                     $query->andFilterWhere(['like', 'ti.' . $prop->key, $this->{$prop->key}]);
                 } else {
                     $query->andFilterWhere(['ti.' . $prop->key => $this->{$prop->key}]);
                 }
             } elseif ($prop->is_eav) {
                 $eavJoinsCount++;
                 $eavTableName = 'eav' . $eavJoinsCount;
                 $key = 'key' . $eavJoinsCount;
                 $query->join('INNER JOIN', "{$object->eav_table_name} {$eavTableName}", $eavTableName . '.object_model_id = ' . $baseModelTableName . ".id AND {$eavTableName}.key=:{$key}", [$key => $prop->key]);
                 if ($prop->value_type === 'STRING' && $prop->property_handler_id !== 3) {
                     $query->andFilterWhere(['like', $eavTableName . '.value', $this->{$prop->key}]);
                 } else {
                     // numeric - direct match
                     $query->andFilterWhere([$eavTableName . '.value' => $this->{$prop->key}]);
                 }
             } elseif ($prop->has_static_values) {
                 $osvJoinsCount++;
                 $osvTableName = 'osv' . $osvJoinsCount;
                 $query->join('INNER JOIN', "object_static_values {$osvTableName}", "{$osvTableName}.object_id={$object->id} AND {$osvTableName}.object_model_id={$baseModelTableName}.id");
                 // numeric - direct match
                 $query->andFilterWhere(["{$osvTableName}.property_static_value_id", $this->{$prop->key}]);
             }
         }
     }
     return $dataProvider;
 }
Пример #22
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Object::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'id_user' => $this->id_user, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'status' => $this->status]);
     $query->andFilterWhere(['like', 'title', $this->title]);
     return $dataProvider;
 }
Пример #23
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = ObjectModel::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['like', 'user_name', $this->user_name])->andFilterWhere(['like', 'auth', $this->auth])->andFilterWhere(['like', 'name', $this->name]);
     return $dataProvider;
 }
Пример #24
0
 public function actionEdit($parent_id, $id = null)
 {
     $object = Object::getForClass(Page::className());
     /** @var null|Page|HasProperties $model */
     $model = new Page();
     $model->published = 1;
     if ($id !== null) {
         $model = Page::findOne($id);
         if ($model === null) {
             throw new NotFoundHttpException();
         }
     }
     $model->parent_id = $parent_id;
     $event = new BackendEntityEditEvent($model);
     $this->trigger(self::BACKEND_PAGE_EDIT, $event);
     $post = \Yii::$app->request->post();
     if ($event->isValid && $model->load($post)) {
         $saveStateEvent = new BackendEntityEditEvent($model);
         $this->trigger(self::BACKEND_PAGE_EDIT_SAVE, $saveStateEvent);
         if ($saveStateEvent->isValid && $model->validate()) {
             $save_result = $model->save();
             $model->saveProperties($post);
             if (null !== ($view_object = ViewObject::getByModel($model, true))) {
                 if ($view_object->load($post, 'ViewObject')) {
                     if ($view_object->view_id <= 0) {
                         $view_object->delete();
                     } else {
                         $view_object->save();
                     }
                 }
             }
             if ($save_result) {
                 $this->runAction('save-info', ['model_id' => $model->id]);
                 Yii::$app->session->setFlash('info', Yii::t('app', 'Object saved'));
                 $returnUrl = Yii::$app->request->get('returnUrl', ['/page/backend/index']);
                 switch (Yii::$app->request->post('action', 'save')) {
                     case 'next':
                         return $this->redirect(['/page/backend/edit', 'returnUrl' => $returnUrl, 'parent_id' => Yii::$app->request->get('parent_id', null)]);
                     case 'back':
                         return $this->redirect($returnUrl);
                     default:
                         return $this->redirect(Url::toRoute(['/page/backend/edit', 'id' => $model->id, 'returnUrl' => $returnUrl, 'parent_id' => $model->parent_id]));
                 }
             } else {
                 \Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot update data'));
             }
         }
     }
     return $this->render('page-form', ['model' => $model, 'object' => $object]);
 }
Пример #25
0
 /**
  * @throws yii\web\ServerErrorHttpException
  */
 public function init()
 {
     parent::init();
     if (null === $this->modelName) {
         throw new yii\web\ServerErrorHttpException('Model name should be set in controller actions');
     }
     if (!is_subclass_of($this->modelName, '\\yii\\db\\ActiveRecord')) {
         throw new yii\web\ServerErrorHttpException('Model class does not exists');
     }
     $this->objectId = Object::getForClass($this->modelName);
     if (null === $this->objectId) {
         throw new yii\web\ServerErrorHttpException('Object does not exists for model.');
     }
 }
Пример #26
0
 public function run()
 {
     app\backend\assets\FrontendEditingAsset::register($this->view);
     $items = [['label' => Icon::show('dashboard') . ' ' . Yii::t('app', 'Backend'), 'url' => ['/backend/']]];
     switch (Yii::$app->requestedRoute) {
         case 'shop/product/list':
             if (isset($_GET['properties'])) {
                 $apply_if_params = [];
                 foreach ($_GET['properties'] as $property_id => $values) {
                     if (isset($values[0])) {
                         $apply_if_params[$property_id] = $values[0];
                     }
                 }
                 if (Yii::$app->response->dynamic_content_trait === true) {
                     $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Edit Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'id' => Yii::$app->response->matched_dynamic_content_trait_model->id]];
                 } else {
                     if (isset($_GET['properties'], $_GET['last_category_id'])) {
                         $items[] = ['label' => Icon::show('puzzle') . ' ' . Yii::t('app', 'Add Dynamic Content'), 'url' => ['/backend/dynamic-content/edit', 'DynamicContent' => ['apply_if_params' => Json::encode($apply_if_params), 'apply_if_last_category_id' => $_GET['last_category_id'], 'object_id' => Object::getForClass(app\modules\shop\models\Product::className())->id, 'route' => 'shop/product/list']]];
                     }
                 }
             } else {
                 // no properties selected - go to category edit page
                 if (isset($_GET['last_category_id'])) {
                     $reviewsLink = $this->getReviewEditParams("Category", intval($_GET['last_category_id']));
                     $cat = app\modules\shop\models\Category::findById($_GET['last_category_id']);
                     $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit category'), 'url' => ['/shop/backend-category/edit', 'id' => $cat->id, 'parent_id' => $cat->parent_id]];
                 }
             }
             break;
         case 'shop/product/show':
             if (isset($_GET['model_id'])) {
                 $reviewsLink = $this->getReviewEditParams("Product", intval($_GET['model_id']));
                 $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit product'), 'url' => ['/shop/backend-product/edit', 'id' => intval($_GET['model_id'])]];
             }
             break;
         case '/page/page/show':
         case '/page/page/list':
             if (isset($_GET['id'])) {
                 $page = app\modules\page\models\Page::findById($_GET['id']);
                 $reviewsLink = $this->getReviewEditParams("Page", $_GET['id']);
                 $items[] = ['label' => Icon::show('pencil') . ' ' . Yii::t('app', 'Edit page'), 'url' => ['/page/backend/edit', 'id' => $page->id, 'parent_id' => $page->parent_id]];
             }
             break;
     }
     if (!empty($reviewsLink)) {
         $items[] = $reviewsLink;
     }
     return $this->render('floating-panel', ['items' => $items, 'bottom' => $this->bottom]);
 }
 public static function editQuery(SearchEvent $event)
 {
     /** @var \app\modules\shop\ShopModule $module */
     $module = \Yii::$app->modules['shop'];
     /** @var \app\modules\shop\ShopModule $module */
     $properties = (new Query())->select('`id`')->from(PropertyStaticValues::tableName())->where('`name` LIKE :q')->addParams([':q' => '%' . $event->q . '%'])->all();
     $event->activeQuery->select('{{%object_static_values}}.object_model_id')->distinct(true)->from(ObjectStaticValues::tableName())->where('{{%object_static_values}}.object_id = :objectId')->addParams([':objectId' => Object::getForClass(Product::className())->id])->andWhere(['in', '{{%object_static_values}}.property_static_value_id', ArrayHelper::getColumn($properties, 'id')]);
     if ($module->allowSearchGeneratedProducts != 1) {
         $event->activeQuery->innerJoin('{{%product}}', '{{%product}}.id = {{%object_static_values}}.object_model_id');
         $event->activeQuery->andWhere(['{{%product}}.parent_id' => 0, '{{%product}}.active' => 1]);
     }
     $event->setFunctionSearch(function ($activeQuery) {
         return ArrayHelper::getColumn($activeQuery->all(), 'object_model_id');
     });
 }
Пример #28
0
 public function actionEdit($id = null)
 {
     $model = new Form();
     if ($id > 0) {
         $model = Form::findOne($id);
     }
     /** @var \app\models\Object $object */
     $object = Object::getForClass(Form::className());
     $propIds = (new Query())->select('property_group_id')->from([ObjectPropertyGroup::tableName()])->where(['and', 'object_id = :object', 'object_model_id = :id'], [':object' => $object->id, ':id' => $id])->column();
     $post = \Yii::$app->request->post();
     $properties = isset($post['Form']['properties']) ? $post['Form']['properties'] : [];
     if ($model->load($post) && $model->validate()) {
         if ($model->save()) {
             $id = $model->id;
             $remove = [];
             $add = [];
             foreach ($propIds as $value) {
                 $key = array_search($value, $properties);
                 if ($key === false) {
                     $remove[] = $value;
                 } else {
                     unset($properties[$key]);
                 }
             }
             foreach ($properties as $value) {
                 $add[] = [$value, $object->id, $id];
             }
             Yii::$app->db->createCommand()->delete(ObjectPropertyGroup::tableName(), ['and', 'object_id = :object', 'object_model_id = :id', ['in', 'property_group_id', $remove]], [':object' => $object->id, ':id' => $id])->execute();
             if (!empty($add)) {
                 Yii::$app->db->createCommand()->batchInsert(ObjectPropertyGroup::tableName(), ['property_group_id', 'object_id', 'object_model_id'], $add)->execute();
             }
             \Yii::$app->session->setFlash('info', Yii::t('app', 'Object saved'));
             $returnUrl = Yii::$app->request->get('returnUrl', ['/backend/form/index', 'id' => $model->id]);
             switch (Yii::$app->request->post('action', 'save')) {
                 case 'next':
                     return $this->redirect(['/backend/form/edit', 'returnUrl' => $returnUrl]);
                 case 'back':
                     return $this->redirect($returnUrl);
                 default:
                     return $this->redirect(Url::toRoute(['/backend/form/edit', 'id' => $model->id, 'returnUrl' => $returnUrl]));
             }
         } else {
             \Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot update data'));
         }
     }
     $items = ArrayHelper::map(PropertyGroup::find()->where('object_id = :object', [':object' => $object->id])->all(), 'id', 'name');
     return $this->render('edit', ['model' => $model, 'items' => $items, 'selected' => $propIds]);
 }
Пример #29
0
 public function actionClearDeleted()
 {
     $time = new \DateTime();
     $days = Yii::$app->getModule('core')->daysToStoreSubmissions;
     $time->sub(new \DateInterval("P{$days}D"));
     /** @var Object $object */
     $object = Object::getForClass(Submission::className());
     if ($object !== null) {
         $submissionIds = Submission::find()->select(['id'])->where('UNIX_TIMESTAMP(`date_received`) < ' . $time->getTimestamp() . ' AND `is_deleted` = \'1\'')->column();
         Review::deleteAll(['submission_id' => $submissionIds]);
         Yii::$app->db->createCommand()->delete($object->column_properties_table_name, ['object_model_id' => $submissionIds]);
         Yii::$app->db->createCommand()->delete($object->eav_table_name, ['object_model_id' => $submissionIds]);
         Yii::$app->db->createCommand()->delete($object->categories_table_name, ['object_model_id' => $submissionIds]);
         ObjectStaticValues::deleteAll(['object_id' => $object->id, 'object_model_id' => $submissionIds]);
         Submission::deleteAll(['id' => $submissionIds]);
     }
 }
Пример #30
0
 /**
  * Поиск связи по модели
  *
  * @param \yii\db\ActiveRecord $model
  * @param boolean $forceDefault Флаг для принудительного возврата модели
  * @return \yii\db\ActiveRecord|null Возвращает модель или null, если ничего не найдено
  */
 public static function getByModel($model = null, $forceDefault = false)
 {
     if (null === $model || !is_object($model)) {
         return null;
     }
     if (null === ($object = Object::getForClass($model::className()))) {
         return null;
     }
     if (null === ($result = static::find()->where(['object_id' => $object->id, 'object_model_id' => $model->id])->one())) {
         if ($forceDefault) {
             $result = new static();
             $result->object_id = $object->id;
             $result->object_model_id = $model->id;
             $result->view_id = 1;
         }
     }
     return $result;
 }