Your IP : 216.73.216.79


Current Path : /var/www/html/dyna-project/controllers/
Upload File :
Current File : /var/www/html/dyna-project/controllers/UserController.php

<?php

namespace app\controllers;

use Yii;
use app\models\User;
use app\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use yii\helpers\Url;
use app\models\ParamList;
use app\models\Log;
use app\models\LogSearch;
use yii\helpers\ArrayHelper;
use yii\data\ArrayDataProvider;
use yii\web\UploadedFile;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller {

    /**
     * {@inheritdoc}
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'only' => ['index', 'create', 'update', 'view'],
                'rules' => [
                    // allow authenticated users
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    //'roles' => ['?'],
                    ],
                // everything else is denied
                ],
            ],
        ];
    }

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

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

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new User();
        $model->created_dt = date("Y-m-d H:i:s");
        $model->created_by = Yii::$app->user->identity->id;
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;
        $model->uuid = Uuid::uuid4();
        $model->status = 1;
        $pwd = Yii::$app->security->generateRandomString(8);
        //$pwd = '123456';
        $model->pwd = \Yii::$app->security->generatePasswordHash($pwd);
        $model->auth_key = \Yii::$app->security->generateRandomString();
        if ($model->load(Yii::$app->request->post())) {

            $model->file = UploadedFile::getInstance($model, 'file');
            if (!empty($model->file)) {
                $file_name = 'uploads/' . date("YmdHis") . '.' . $model->file->extension;
                if ($model->file->saveAs($file_name))
                    $model->img_url = $file_name;
            }

            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog('user', 'create', $model->id);

                $ParamList = new ParamList();

                //send email
                $email_content = '<html>
                <body>
                    <div style="font-family: \'Century Gothic\', CenturyGothic, AppleGothic, sans-serif; font-size: 14px;background-color:rgb(234,234,234);padding:2em 0;">
                        <div style="width:70%;background-color:white;margin:0 auto;padding:5em 5em 5em 5em;border:1px solid #ccc;">
                            <p>Hi ' . $model->name . ',</p>
                            <p>Welcome to ' . Yii::$app->params['systemName'] . '!</p>
                            <p>You now can access the system as a ' . $ParamList->getlabel(2, $model->role) . ' using below details:</p>
                            <p>URL: <a href="' . Url::base(true) . '" target="_blank">' . Url::base(true) . '</a></p>
                            <p>Email: ' . $model->email . '</p>
                            <p>Password: ' . $pwd . '</p>
                            <p>- Admin -</p>
                        </div>
                    </div>
                </body>
            </html>';

                /* Yii::$app->mailer->compose()
                  ->setFrom(Yii::$app->params['senderEmail'])
                  ->setTo($model->email)
                  ->setSubject('Blunet Project System Login Details')
                  ->setHtmlBody($email_content)
                  ->send(); */

                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                mail($model->email, 'Blunet Project System Login Details', $email_content, $headers);

                $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'User have been created',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('user/index') . "';});");
            }
        }

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

    /**
     * Updates an existing User 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($uuid) {
        $model = $this->findModel($uuid);
        $model->updated_dt = date("Y-m-d H:i:s");
        $model->updated_by = Yii::$app->user->identity->id;
        if ($model->load(Yii::$app->request->post())) {
            $model->file = UploadedFile::getInstance($model, 'file');
            if (!empty($model->file)) {
                $file_name = 'uploads/' . date("YmdHis") . '.' . $model->file->extension;
                if ($model->file->saveAs($file_name))
                    $model->img_url = $file_name;
            }
            if ($model->save()) {
                $Log = new Log();
                $Log->insertlog('user', 'update', $model->id);
                $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('user/index') . "';});");
            }
        }
        return $this->render('update', ['model' => $model]);
    }

    /**
     * Deletes an existing User 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 = $_POST['id'];
        $status = 'failed';
        $model = User::findOne($id);
        if (!empty($model)) {
            $model->status = 0;
            if ($model->save(false)) {
                $Log = new Log();
                $Log->insertlog('user', 'delete', $model->id);
                $status = 'success';
            }
        }
        return $status;
    }

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

    public function actionProfile() {
        if (($model = User::findOne(Yii::$app->user->identity->id)) !== null) {
            if ($model->load(Yii::$app->request->post())) {
                $model->file = UploadedFile::getInstance($model, 'file');
                if (!empty($model->file)) {
                    $file_name = 'uploads/' . date("YmdHis") . '.' . $model->file->extension;
                    if ($model->file->saveAs($file_name))
                        $model->img_url = $file_name;
                }
                if ($model->save()) {
                    $Log = new Log();
                    $Log->insertlog('user', 'update', $model->id);
                    $this->getView()->registerJs("swal.fire({position: 'center-center',type: 'success',title: 'Data has been saved',showConfirmButton: false,timer: 1500,}).then(function(result){window.location = '" . Url::toRoute('user/profile') . "';});");
                }
            }
            return $this->render('profile', ['model' => $model]);
        }
    }

    public function actionChangepwd() {
        $output = "";
        $new_pwd = $_POST['new_pwd'];
        if (($model = User::findOne(Yii::$app->user->identity->id)) !== null) {
            $model->updated_dt = date("Y-m-d H:i:s");
            $model->updated_by = Yii::$app->user->identity->id;
            $model->pwd = \Yii::$app->security->generatePasswordHash($new_pwd);
            if ($model->save(false)) {
                $Log = new Log();
                $Log->insertlog('profile', 'update password', $model->id);
                $output = 'success';
            } else
                $output = 'failed';
        }
        return $output;
    }

    public function actionAdminresetpwd() {
        $output = "failed";
        if (($model = User::findOne($_POST['id'])) !== null) {
            $pwd = Yii::$app->security->generateRandomString(8);
            $model->pwd = \Yii::$app->security->generatePasswordHash($pwd);
            if ($model->save(false)) {
                $email_content = '<html>
                        <body>
                            <div style="font-family: \'Century Gothic\', CenturyGothic, AppleGothic, sans-serif; font-size: 14px;background-color:rgb(234,234,234);padding:2em 0;">
                                <div style="width:70%;background-color:white;margin:0 auto;padding:0em 5em 5em 5em;border:1px solid #ccc;">
                                    <p><center><img src="' . Url::base(true) . '/images/netbizlogo.png"></center>Hi ' . $model->name . ',</p>
                                    <p>Your password has been reset. You can access the system now using below details :</p>
                                    <p>URL: <a href="' . Url::base(true) . '" target="_blank">' . Url::base(true) . '</a></p>
                                    <p>Email: ' . $model->email . '</p>
                                    <p>Password: ' . $pwd . '</p>
                                    <p>- Admin -</p>
                                </div>
                            </div>
                        </body>
                    </html>';
                if (Yii::$app->mailer->compose()
                                ->setFrom(Yii::$app->params['senderEmail'])
                                ->setTo($model->email)
                                ->setBcc(Yii::$app->params['bccEmail'])
                                ->setSubject('Reset Password')
                                ->setHtmlBody($email_content)
                                ->send()) {
                    $output = 'success';
                }
            }
        }
        return $output;
    }

}