HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux dev1 5.15.83-1-pve #1 SMP PVE 5.15.83-1 (2022-12-15T00:00Z) x86_64
User: safarimaris (1000)
PHP: 7.2.34-54+ubuntu22.04.1+deb.sury.org+1
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,
Upload Files
File: /home/safarimaris/home/safarimaris/backend/controllers/ProductController.php
<?php

namespace backend\controllers;

use common\models\Days;
use common\models\Entity;
use common\models\GalleryImage;
use common\models\Site;
use Yii;
use common\models\Product;
use app\models\ProductSearch;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Url;
use zxbodya\yii2\galleryManager\GalleryManager;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'view', 'create', 'update', 'delete', 'galleryApi', 'galleryDaysApi', 'sites', 'clone', 'change'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'galleryApi' => [
                'class' => \zxbodya\yii2\galleryManager\GalleryManagerAction::className(),
                'types' => [
                    'product' => Product::className()
                ]
            ],
            'galleryDaysApi' => [
                'class' => \zxbodya\yii2\galleryManager\GalleryManagerAction::className(),
                'types' => [
                    'days' => Days::className()
                ]
            ],
        ];
    }

    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->pagination->pageSize=50;
        Url::remember();

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Product(array('scenario' => 'create'));
        $modelDays= [new Days()];
        if ($model->load(Yii::$app->request->post())) {
            $modelDays = Product::createMultiple(Days::classname());
            Product::loadMultiple($modelDays, Yii::$app->request->post());

            $valid = $model->validate();
            $valid = Product::validateMultiple($modelDays) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        foreach ($modelDays as $modelDay) {
                            $modelDay->productId = $model->id;
                            if (! ($flag = $modelDay->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(Url::previous());
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        } else {
            return $this->render('create', [
                'model' => $model,
                'modelDays' => (empty($modelDays)) ? [new Days()] : $modelDays
            ]);
        }
    }

    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $modelDays = $model->days;
        if (empty($model->seoUrl)){
            $model->seoUrl = '-' . $model->entity->seoUrl;
        }

        if ($model->load(Yii::$app->request->post())) {
            $oldIDs = ArrayHelper::map($modelDays, 'id', 'id');
            $modelDays = Product::createMultiple(Days::classname(), $modelDays);
            Product::loadMultiple($modelDays, Yii::$app->request->post());
            $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelDays, 'id', 'id')));

            if($model->seoUrl == '-'.$model->entity->seoUrl){
                $model->seoUrl = null;
            }
            $valid = $model->validate();
            $valid = Product::validateMultiple($modelDays) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        if (! empty($deletedIDs)) {
                            foreach ($deletedIDs as $deleteId){
                                $modelDeleteDays = Days::findOne($deleteId);
                                @unlink($modelDeleteDays->behaviors()['galleryBehavior']['directory'].'/'.$deleteId);
                                GalleryImage::deleteAll(['type' => 'days', 'ownerId' => $deleteId]);
                            }
                        }
                        foreach ($modelDays as $modelDay) {
                            if (empty($modelDay->name)){
                                continue;
                            }
                            $modelDay->productId = $model->id;
                            if (! ($flag = $modelDay->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(Url::previous());
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        }

        return $this->render('update', [
            'model' => $model,
            'modelDays' => (empty($modelDays)) ? [new Days()] : $modelDays
        ]);
    }

    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(Url::previous());
    }

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            $model->setScenario('update');
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSites($entityId)
    {
        $entity = Entity::findOne($entityId);
        $items = Site::find()->where(['countryId' => $entity->countryId])->orderBy('name')->all();

        foreach($items as $item) {
            echo '<label><input name="Product[site_ids][]" value="'.$item->id.'" type="checkbox"> '.$item->name.'</label>';
        }
    }

    /**
     * Clone an existing Tour model.
     * @param integer $id
     * @throws
     * @return mixed
     */
    public function actionClone($id)
    {

        $model = $this->findModel($id);
        $clone = new Product(
            $model->getAttributes() // get all attributes and copy them to the new instance
        );
        $clone->id = null;
        $clone->name = sprintf('%s %s', 'COPY', $model->name);
        $clone->site_ids = $model->site_ids;
        $clone->feature_ids = $model->feature_ids;
        $clone->tag_ids = $model->tag_ids;
        $clone->seoUrl = null;

        //copy images
        $ext = pathinfo($model->logo, PATHINFO_EXTENSION);
        $clone->logo = uniqid().'.'.$ext;
        @copy(Yii::getAlias( '@imgPath/product/' .  $model->logo), Yii::getAlias( '@imgPath/product/' . $clone->logo));
        foreach (Yii::$app->params['thumbs'] as $k => $v) {
            @copy(Yii::getAlias( '@imgPath/product/' . $k.'-'. $model->logo), Yii::getAlias( '@imgPath/product/' . $k.'-'. $clone->logo));
        }

        $clone->save();

        return $this->redirect(Url::previous());
    }

    /**
     * Change an existing Product model.
     * @throws
     * @return mixed
     */
    public function actionChange()
    {
        $post = Yii::$app->request->post();
        $model = $this->findModel($post['id']);
        $model->divebookerId = $post['divebookerId'] ?: null;
        $model->save(false);
    }
}