Your IP : 216.73.216.79


Current Path : /var/www/html/swcorpdataraya/backend/controllers/frontend/
Upload File :
Current File : /var/www/html/swcorpdataraya/backend/controllers/frontend/FrontendSiteController.php

<?php

namespace backend\controllers\frontend;

use Yii;
use backend\models\frontend\FrontendSite;
use backend\models\frontendpage\FrontendPage;
use backend\models\frontend\FrontendSiteSearch;
use backend\modules\mimin\components\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\components\AccessRule;
use yii\helpers\Url;

/**
 * FrontendSiteController implements the CRUD actions for FrontendSite model.
 */
class FrontendSiteController extends Controller {

    /**
     *
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'POST'
                    ]
                ]
            ]
        ];
    }

    public function createUrl() {
        
    }

    /**
     * Lists all FrontendSite models.
     *
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new FrontendSiteSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider]);
    }

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

    /**
     * Creates a new FrontendSite model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate() {
        $model = new FrontendSite();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->getView()->registerJs("swal.fire({
                    title:'Saved',
                    icon: 'success', 
                    text: 'Data has been saved successfully', 
                }).then(function(result){
                        window.location = '" . Url::toRoute(['index']) . "';
                });");
        }
        return $this->render('create', ['model' => $model]);
    }

    /**
     * Updates an existing FrontendSite 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);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->getView()->registerJs("swal.fire({
                    title:'Saved',
                    icon: 'success', 
                    text: 'Data has been saved successfully', 
                }).then(function(result){
                        window.location = '" . Url::toRoute(['index']) . "';
                });");
        }
        return $this->render('update', ['model' => $model]);
    }

    /**
     * Deletes an existing FrontendSite model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param integer $id
     * @return mixed
     */
    public function actionDelete() {
        $id = $_POST['id'];
        $status = 'failed';
        if ($this->findModel($id)->delete())
            $status = 'success';
        return $status;
    }

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

    public function actionSetDefaultSite() {
        $siteid = Yii::$app->request->get('site_id');
        /* reseting the default value */
        $siteDefault = FrontendSite::findOne([
                    'site_default' => 1
        ]);
        if (!empty($siteDefault)) {
            $siteDefault->site_default = 0;
            $siteDefault->update();
            return $this->actionIndex();
        }
        /* setting the default value */
        $siteSetDefault = FrontendSite::find()->where('site_id = :siteid', [
                    ':siteid' => $siteid
                ])->one();
        $siteSetDefault->site_default = 1;
        $siteSetDefault->update();

        return $this->actionIndex();
    }

     /**
     * Finds the FrontendSite model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer 
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDuplicate($id) {
        
        //get site
        $sites = FrontendSite::findOne($id);

        if(empty($sites)) {
            throw new \Exception("Site id don't exist");
        }
        //copy pages to site
        yii::$app->db->transaction(function($db) use ($sites, $id) {
            //create new site
            $site = new FrontendSite();
            $site->site_name = $sites->site_name . '_' . time();
            $site->site_default = 0;
            $site->site_theme = $sites->site_theme;
            $site->slug_enable = $sites->slug_enable;
            $site->site_slug = $sites->site_slug . '_' . time();

            if(!$site->save()) {
                throw new \Exception('Cannot duplicate site' . json_encode($site->errors));
            }

            //get all pages
            $pages =  FrontendPage::find()->where(['site_id' => $id])->all();

            foreach($pages as $page) {
                // $page->page_id
                $newpage = new FrontendPage();
                $newpage->site_id = $site->site_id;
                $newpage->page_name = $page->page_name;
                $newpage->page_setup = $page->page_setup;

                if(!$newpage->save()) {
                    throw new \Exception("Cannot duplicate page, Error:" . json_encode($newpage->errors));
                }
            }
        });

        return $this->redirect(['index']);
    }

    /**
     * Purge Cache in frontend/runtime/frontendpage
     * @return void
     */
    public function actionPurgeCache() {

        try {
            $file = '';
            $url = Url::to(['frontend/frontend-site/index']);
            $nonce = Yii::$app->params['nonce'];
            $message = "Cache Clear!";

            foreach(glob("../../frontend/runtime/frontendpage/*") as $f) {
                    
                    $regex_arr = [
                        '/\d+_\d+\.json/',
                        '/\d+_\d+-theme-setup\.php/',
                        '/\d+_\d+-setup\.php/',
                        '/\d+_\d+-header\.php/',
                        '/\d+_\d+-content-\d+\.php/',
                        '/\d+_\d+-footer\.php/',
                    ];
        
                    // delete content
                   
                    foreach($regex_arr as $regex) {
                        if(preg_match($regex, $f)) {
                            $file .=  $f . "<br>";
                            unlink($f);
                        }
                    }
                }

                if(empty($file)) {
                    $file = 'Cache list empty!';
                    $message = "No cached to clear";
                }

            $html = 
                <<<HTML
                    <div class="alert alert-info">
                    $message
                    <br>
                    Redirect in <span id="counter">5</span> second
                    </div>
                    <pre>$file</pre>
                    <script nonce="$nonce">
                        setInterval(function() {
                            var div = document.querySelector("#counter");
                            var count = div.textContent * 1 - 1;
                            div.textContent = count;
                            if (count <= 0) {
                                window.location.replace("$url");
                            }
                        }, 1000);
                    </script>
                HTML
            ;
            
            return $this->renderContent($html);
        
        } catch (\Throwable $t) {
            die($t->getMessage());
        }
    }

}