Your IP : 216.73.216.79


Current Path : /var/www/html/sprm/backend/controllers/
Upload File :
Current File : /var/www/html/sprm/backend/controllers/SiteController.php

<?php

namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use common\components\AccessRule;
use common\models\User;
use yii\web\Controller;
use common\models\LoginForm;
use backend\models\PasswordResetRequestForm;
use backend\models\ResetPasswordForm;
use yii\filters\VerbFilter;
use backend\models\EventSearch;
use backend\models\LeaveAppSearch;
use backend\controllers\Setup;
use yii\helpers\Json;
use backend\models\LoginSkin;
use backend\models\SignupForm;
use backend\models\StaffDetail;
use backend\models\User as UserValidate;
//use backend\models\FileSurvey;

//use yii\web\AssetBundle;
/**
 * Site controller
 */
class SiteController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'ruleConfig' => [
                    'class' => AccessRule::className(),
                ],
                'rules' => [
                    [
                        'actions' => ['login','login-responden', 'signup','aktivasi', 'request-password-reset', 'reset-password', 'captcha', 'error','flot-data','activate','validate','sso-login','iframe'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['login','index', 'create', 'update', 'view','flot-data','error','logout','flot-data', 'content-preview'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    // 'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex($tab = '') {
        if ($tab == '')
            $tab = 1;
        $data['tab'] = $tab;

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

    public function actionIframe() {
        $this->layout = 'empty';  
        $model = new LoginForm(); 

        return $this->render('iframe', [
                            'model' => $model,
                ]);
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */


    public function actionAktivasi() {

        $this->layout = 'empty';

            $model = new LoginForm();
            $modelUser = new User();
            $modelForgotPass = new PasswordResetRequestForm;
            $modelAktivasi = new SurveyMatched();
            $modelSkin = LoginSkin::find()->where(['status' => 1])->one();
            $modelValidate = new UserValidate();
               
                    return $this->render('aktivasi', [
                            'model' => $model,
                            'modelUser' => $modelUser,
                            'modelForgotPass' => $modelForgotPass,
                            'aktivasi' => $modelAktivasi,
                            'skin' => $modelSkin,
                            'validate' => $modelValidate,
                            'survey' => $modelFileSurvey,

                        ]);
                
    }

    public function actionSignup() {

        $this->layout = 'empty';

        $model = new SignupForm();
        $modelSkin = LoginSkin::find()->where(['status' => 1])->one();
        $model1 = new LoginForm();
        $modelUser = new User();
        $modelForgotPass = new PasswordResetRequestForm;
        $modelAktivasi = new SurveyMatched();
        $modelSkin = LoginSkin::find()->where(['status' => 1])->one();
        $modelValidate = new UserValidate();
            
        if ($model->load(Yii::$app->request->post())) {

            if ($model->signup())

                $checkuser = User::find()->where( [ 'username' => $model->username ] )->one();
                $insertuserinfo = Yii::$app->db->createCommand()->insert('dmg_user_info',['userid'=>$checkuser->id])->execute();
                $checkuserinfo = StaffDetail::find()->where( [ 'userid' => $checkuser->id ] )->one();
                $insertrespondenaccess = Yii::$app->db->createCommand()->insert('dmg_staff_access',['staff_info_id'=>$checkuserinfo->id,'role_code'=>'SV011'])->execute();
                
                Yii::$app->session->setFlash('success');

                return $this->redirect(array('site/login','signupconfirm'=>1));
            

                if ($model->load(Yii::$app->request->post()) && $model->login()) {
                    return $this->goBack();
                }else{
                    return $this->render('login', [
                            'model' => $model,
                            'modelUser' => $modelUser,
                            'modelForgotPass' => $modelForgotPass,
                            'aktivasi' => $modelAktivasi,
                            'skin' => $modelSkin,
                            'validate' => $modelValidate,
                            'survey' => $modelFileSurvey,
                        ]);
                }
            
        }
        return $this->render('signup', [
                    'model' => $model,
                    'skin' => $modelSkin,
                    'signupconfirm' => true,
        ]);
    }

    

    public function actionLogin() {

        $this->layout = 'empty';

        if (!Yii::$app->user->isGuest) {
            $this->goBack();
        }
            $model = new LoginForm();
            $modelUser = new User();
            $modelForgotPass = new PasswordResetRequestForm;
            $modelSkin = LoginSkin::find()->where(['status' => 1])->one();
            $modelValidate = new UserValidate();
            

                if ($model->load(Yii::$app->request->post()) && $model->login()) {

                    return $this->goBack();

                }else{
            
                    return $this->render('login', [
                            'model' => $model,
                            'modelUser' => $modelUser,
                            'modelForgotPass' => $modelForgotPass,
                            'skin' => $modelSkin,
                            'validate' => $modelValidate,
                        ]);
                }
    }

   
    public function actionLogout() {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionRequestPasswordReset() {

        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', Yii::t('app', 'Sila periksa emel anda untuk tindakan seterusnya.'));
                return $this->goHome();
            }
            return $this->refresh();
        } else {

            return $this->render('requestPasswordResetToken', [
                        'model' => $model,
            ]);
        }
    }

    /**
    * Resets password.
    *
    * @param string $token
    * @return mixed
    * @throws BadRequestHttpException
    */
    public function actionResetPassword($token) {
        $this->layout = 'empty';
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            \Yii::$app->session->setFlash('success', 'Kata Laluan Baru berjaya disimpan.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
                    'model' => $model,
        ]);
    }

    public function actionForgotPassword() {
        $modelUser = new User();

        if (isset($_POST['email'])) {
            $mailTo = $_POST['email'];

            $checkUser = User::find()->where("email='$mailTo'")->one();
            if (count($checkUser) > 0) {
                $emailPassword = Yii::$app->mailer->compose('email')
                        ->setFrom(Yii::$app->params['adminEmail'])
                        ->setTo($mailTo) //replace email sini untuk testing
                        ->setSubject('eSurvey Admin - Terlupa kata laluan')
                        ->setHtmlBody('Kata Laluan baru: 12345qwer')
                        ->send();

                $checkUser->password_hash = Yii::$app->security->generatePasswordHash("12345qwer");
                $checkUser->update();
                return "BERJAYA\nAn emel telah dihantar.";
            } else {
                return "GAGAL\nEmel ini tidak wujud di dalam sistemxxxxx";
            }
        }
    }
    
    
     public function actionGetMessage()
    {
        $messageList = Message::model()->findAll(array(
                            'condition' => 'toUserId = :myId AND new = 1',
                            'order' => 'id DESC',
                            'params' => array(':myId' => Yii::app()->user->_id)
                        ));
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        echo "retry: 10000\n"; // Optional. We tell the browser to retry after 10 seconds
        if(count($messageList)) {
            foreach($messageList as $key => $message) {
                echo "data: <p>" . $message->message . "</p>\n";
            }
            //Now we run a bulk update query in order to flag the just retrieved messages (new = 0)
            $sql = 'UPDATE Message
                        SET new = 0
                        WHERE toUserId = ' . Yii::app()->user->_id;
            $command = Yii::app()->db->createCommand($sql);
            $command->execute();
        }
        flush();
    }
    
    public function actionFlotData($start=null,$end=null)
    {   
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
       
        $dash = new DashboardSetting();
        
        /* setting flot status */
        $dash->flot = true;
        
        /* caching */
        $cache = \Yii::$app->cache;
        $fCache = $cache['fdata'];
        
        if($fCache == FALSE)
        {
            $fdata = $dash->flotData();
            $cache->set('fdata',$fdata,100);
        }else{
            $fdata = $fCache;
        }

        $jCache = $cache['json'];
        
        if( $jCache==FALSE || !empty($start) )
        {
            /* start chart date One month interval */
            $start_date = !empty($start) ? $start : "01-".date('m-Y');
            $start_time = strtotime($start_date);
            $end_time = strtotime("+1 month", $start_time);
            
            /* fetch flot data as json */
            $jarray = array();

            foreach ($fdata as $fkey => $fval)
            {
                foreach($fval->createCommand()->queryAll() as $b)
                {
                $arr[$fkey][$b['date']] = [$b['date'],$b['cnt'] ];
                }
            }

            /* combining date and chart date value */
            foreach($arr as $akey => $aval)
            {
                for($i=$start_time; $i<$end_time; $i+=86400)
                {
                    $jarray[$akey][date('Y-m-d',$i)] = "0";
                    $jarray[$akey][$aval[date('Y-m-d',$i)][0]] = $aval[date('Y-m-d',$i)][1];
                }
            }

            /* convert to key pair date and cnt value */
            foreach($jarray as $jkey => $jval)
            {
                $z = 0;
                foreach($jval as $date => $datval)
                {
                $jsonObj[$jkey][$z]['date'] = $date;
                $jsonObj[$jkey][$z]['cnt'] = $datval;
                $z++;}
            }

            $cache->set('json',$jsonObj,500);
            
        }else{
            $jsonObj = $jCache; 
        }
        return Json::encode($jsonObj);
    }
    

  public function actionSsoLogin($token)
    {
        if ($token){
             $user = new UserValidate;
             $claims = $user->getUserbyToken($token);
             Yii::$app->user->login($claims, 0);
             Yii::$app->session->set('ssotoken', $token);

            return $this->goBack();
        }
    }

    public function actionContentPreview($id=null, $lang=null){
        $bs4 = '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">';
        
        if(empty($id)){
            return $bs4;
        }
        $article = \backend\models\ContentArticle::findOne($id);
        if (!empty($article)) {
            
            if($lang === 'en'){
                return $bs4 . $article->content_article_content_en;
            }
            if($lang === 'ch'){
                return $bs4 . $article->content_article_content_ch;
            }

            return $bs4 . $article->content_article_content_my;
        }
    }
}