Your IP : 216.73.216.79


Current Path : /var/www/html/brspace/backend/modules/firstTimeSetup/controllers/
Upload File :
Current File : /var/www/html/brspace/backend/modules/firstTimeSetup/controllers/SetupController.php

<?php

namespace backend\modules\firstTimeSetup\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use backend\modules\theme\models\ThemeSetting;
use backend\modules\theme\models\ThemeRule;
use backend\modules\firstTimeSetup\models\FrontendSettings;
use common\components\HelpersFunctions;
use backend\modules\mimin\models\User;
use backend\modules\mimin\models\AuthAssignment;


/**
 * ContentTagController implements the CRUD actions for ContentTag model.
 */
class SetupController extends Controller {

    const FRONTEND_SETTING_ID = 2;

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

    /**
     * Lists all ContentTag models.
     * @return mixed
     */
    public function actionIndex() {

        $this->layout = false;

        return $this->render('index');
    }

    /**
     * Displays a single ContentTag model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id) {
        $model = $this->findModel($id);
        
        return $this->render('view', [
                    'model' => $model
        ]);
    }

    /**
     * Creates a new ContentTag model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        try {
            $post = Yii::$app->request->post();
            $setting_map = $this->settingMap();
       
            if(Yii::$app->request->post()) {

                foreach($setting_map as $key => $params) {
                    
                    if($params['source'] === 'backend') {

                        if(!empty($post[$key])) {
                            $this->saveSourceBackend($setting_map, $params, $post[$key]);
                        }

                        if(is_array($_FILES)) {
                            $this->saveFileSourceBackend($params);
                        }
                    }

                    if($params['source'] === 'frontend') {

                        /** file upload **/
                        if(is_array($_FILES)) {
                            $this->saveFileSourceFrontend($key, $params);                            
                            $this->saveSourceFrontend($setting_map, $params['key'], $params['path'] . $params['name']);
                        }

                        if(!empty($post[$key])) {
                            $this->saveSourceFrontend($setting_map, $params['key'], $post[$key]);
                        }
                    }
                }

                $this->generateCss();

                /** save user **/
                $this->saveSourceUser($post);
                
                return $this->asJson([
                    'success' => true,
                    'payload' => $post
                ]);
            }

        } catch(\Throwable $t) {
            Yii::$app->response->statusCode = 500;
            
            return $this->asJson([
                'success' => false,
                'error' => $t->getMessage()
            ]);
        }
    }

    private function saveSourceBackend($setting_map, $params, $value): void {
        
        $model = new ThemeSetting();
        
        /**  check if setting exist **/
        $exist = $this->settingExist($params['key'], $params['rule_id'], $model);
        
        if(!empty($exist)){
            //update
            $model = $exist;
        } 

        /** save only if value is present **/
        if(!empty($value)) {
            
            $model->setting_param_name = $params['key'];
            $model->setting_param_type = $params['type'];
            $model->setting_param_value = $value;
            $model->setting_rule_id = $params['rule_id'];

            if(!$model->save()) {
                throw new \Exception("Error saving First time setup :- " . json_encode($model->errors) );
            }
        }
    }

    private function saveFileSourceBackend($params): void {
        /** file upload **/
        if(isset($params['path'])) {
            if ($_FILES[$params['key']]['error'] === 0) {
                $source = $_FILES[$params['key']]['tmp_name'];

                if(isset($params['path']) && isset($params['name'])) {
                    //compress it
                    HelpersFunctions::compressImage($source, $params['path'], $params['name'], 75);
                }
            }
        }
    }

    private function saveFileSourceFrontend($key, $params): void {
        /** file upload **/
        if(isset($params['path'])) {
            if ($_FILES[$key]['error'] === 0) {
                $source = $_FILES[$key]['tmp_name'];

                if(isset($params['path']) && isset($params['name'])) {
                    //compress it
                    HelpersFunctions::compressImage($source, $params['path'], $params['name'], 75);
                }
            }
        }
    }

    private function saveSourceFrontend($setting_map, $params, $value): void {
        
        $model = FrontendSettings::findOne(self::FRONTEND_SETTING_ID);

            /** save only if value is present **/
        $model->{$params} = $value;
        
        if(!$model->save()) {
            throw new \Exception("Error saving First time setup :- " . json_encode($model->errors) );
        }
    }

    private function saveSourceUser($post): bool {
        
        if(empty($post['username']) ||  empty($post['username']) || empty($post['email']) || empty($post['password']) ) {
            return false;
        }
        
        $model = new User();

        $model->username = $post['username'];
        $model->fullname = $post['fullname'];
        $model->email = $post['email'];
        $model->userroles = 'super-admin';
        $model->setPassword($post['password']);
        $model->created_dt = date('Y-m-d');
        $model->status = 10;
        
        if(!$model->save()) {
            throw new \Exception("Error saving First time setup :- " . json_encode($model->errors) );
        }

        /** assign auth **/
        $authAssignment2 = new AuthAssignment([
            'user_id' => $model->id,
        ]);
        $authAssignment2->item_name = 'super-admin';
        $authAssignment2->created_at = time();

        if(!$authAssignment2->save()) {
            throw new \Exception("Error saving First time setup :- " . json_encode($authAssignment2->errors) );
        }
    }

    /**
     * Updates an existing ContentTag model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                return $this->redirect(['index']);
            }
        }
        return $this->render('update', ['model' => $model,]);
    }

    /**
     * Deletes an existing ContentTag model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id) {
        ContentTagTranslation::deleteAll(['tag_translation_parent_id' => $id]);
        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

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

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }

    private function settingMap() {

        $config = \Yii::$app->params['templateSetting'];
        $configpath = $config['sideBgUpload'];
        $filename = $config['sideBgFileName'];

        return [
            'site_title' => [
               'key' => 'page-title',
               'type' => 'text',
               'rule_id' => 9000,
               'source' => 'backend'
            ],
            'description' => [
               'key' => 'description',
               'type' => 'text',
               'rule_id' => 9000,
               'source' => 'backend'
            ],
            'author' => [
               'key' => 'author',
               'type' => 'text',
               'rule_id' => 9000,
               'source' => 'backend'
            ],
            'cms_title' => [
               'key' => 'metadata_page_title',
               'type' => 'text',
               'source' => 'frontend'
            ],
            'favicon' => [
               'key' => 'favicon',
               'type' => 'text',
               'path' => './',
               'name' => 'favicon.ico',
               'source' => 'backend'
            ],
            'sidebar_logo' => [
               'key' => 'sidebar_logo',
               'type' => 'text',
               'path' => $configpath . '/',
               'name' => $filename,
               'source' => 'backend'
            ],
            'dashboard_banner' => [
               'key' => 'dashboard_banner',
               'type' => 'text',
               'path' => $configpath . '/',
               'name' => 'cmsbanner.jpg',
               'source' => 'backend'
            ],
            'login_background' => [
               'key' => 'login_background',
               'type' => 'text',
               'path' => $configpath . '/',
               'name' => 'login_background.jpg',
               'source' => 'backend'
            ],
            'login_logo' => [
               'key' => 'login_logo',
               'type' => 'text',
               'path' => $configpath . '/',
               'name' => 'login_logo.png',
               'source' => 'backend'
            ],
            'login_title' => [
               'key' => 'title',
               'type' => 'text',
               'rule_id' => 2,
               'source' => 'backend'
            ],
            'login_message' => [
               'key' => 'description',
               'type' => 'text',
               'rule_id' => 2,
               'source' => 'backend'
            ],
            'login_copyright' => [
               'key' => 'copyright',
               'type' => 'text',
               'rule_id' => 2,
               'source' => 'backend'
            ],
            'cms_login_title' => [
               'key' => 'logintitle',
               'type' => 'text',
               'source' => 'frontend'
            ],
            'cms_login_message' => [
               'key' => 'loginmessage',
               'type' => 'text',
               'source' => 'frontend'
            ],
            'cms_logo' => [
               'key' => 'logo',
               'path' => '../uploads/',
               'name' => 'img-logo' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_login_logo' => [
               'key' => 'loginlogo',
               'path' => '../uploads/',
               'name' => 'img-logo' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_login_background' => [
               'key' => 'loginbg',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_loggedin_logo' => [
               'key' => 'loggedinlogo',
               'path' => '../uploads/',
               'name' => 'img-logo' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_top_logo' => [
               'key' => 'topbarlogo',
               'path' => '../uploads/',
               'name' => 'img-top-logo' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_preloader_logo' => [
               'key' => 'preloaderlogo',
               'path' => '../uploads/',
               'name' => 'img-preloader-logo' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_preloader_background' => [
               'key' => 'preloaderbg',
               'path' => '../uploads/',
               'name' => 'img-preloader-logo' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_footer_logo' => [
               'key' => 'footerlogo',
               'path' => '../uploads/',
               'name' => 'img-footer-logo' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_primary_color' => [
               'key' => 'color_primary',
               'type' => 'text',
               'source' => 'frontend'
            ],
            'cms_secondary_color' => [
               'key' => 'color_secondary',
               'type' => 'text',
               'source' => 'frontend'
            ],
            'cms_favicon' => [
               'key' => 'favicon',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_register_logo' => [
               'key' => 'registerlogo',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_register_logo' => [
               'key' => 'registerlogo',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_register_background' => [
               'key' => 'registerbg',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_chatbot_logo' => [
               'key' => 'chatbotlogo',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_chatbot_main_icon' => [
               'key' => 'chatbotmainicon',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_chatbot_admin_icon' => [
               'key' => 'chatbotadminicon',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'cms_chatbot_user_icon' => [
               'key' => 'chatbotusericon',
               'path' => '../uploads/',
               'name' => 'img-favicon-' . round(microtime(true)) . '.jpg',
               'source' => 'frontend'
            ],
            'username' => [
               'key' => 'username',
               'type' => 'text',
               'source' => 'user'
            ],
            'fullname' => [
               'key' => 'fullname',
               'type' => 'text',
               'source' => 'user'
            ],
            'email' => [
               'key' => 'email',
               'type' => 'text',
               'source' => 'user'
            ],
            'password' => [
               'key' => 'email',
               'type' => 'text',
               'source' => 'user'
            ],
        ];
    }

    private function settingExist($param, $rule_id, $model) {
        $exist = $model::find()->where(['setting_param_name' => $param, 'setting_rule_id' => $rule_id])->one();

        if($exist) {
            return $exist;
        }

        return false;
    }

    private function generateCss() {
        $path = dirname(Yii::getAlias('@app')) . DIRECTORY_SEPARATOR . 'www' . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'theme-module.css';

        $cssrule = ThemeRule::find()->where([
                    'rule_status' => 1
                ])->all();
        $content = '';
        foreach ($cssrule as $css) {
            $themes = ThemeSetting::settingArray()[$css->rule_id] ?? [];
            $cconts = $css->rule_content;
            foreach ($themes as $tkey => $tval) {

                if (is_array($tval) && $tval['type'] === 'unit') {
                    $tval = $tval['value'] . $tval['unit'];
                }

                $cconts = strtr($cconts, [
                    "{{{$tkey}}}" => $tval
                ]);
            }
            $content .= PHP_EOL . $cconts . PHP_EOL;
        }
        file_put_contents($path, $content);
    }
}