Your IP : 216.73.216.79


Current Path : /var/www/html/kpwkmintranet/backend/controllers/frontend/
Upload File :
Current File : /var/www/html/kpwkmintranet/backend/controllers/frontend/FrontendContentAssignController.php

<?php

namespace backend\controllers\frontend;

use Yii;
use backend\models\frontendcontentassign\FrontendContentAssign;
use backend\models\frontendcontentassign\FrontendContentAssignSearch;
use backend\models\frontendcontent\FrontendContent;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\db\Query;
use backend\models\frontendpage\FrontendPage;
use yii\filters\AccessControl;
use common\components\AccessRule;
use common\components\PortalDBContent;

/**
 * FrontendContentAssignController implements the CRUD actions for FrontendContentAssign model.
 */
class FrontendContentAssignController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::class,
                'ruleConfig' => [
                    'class' => AccessRule::class,
                ],
                'rules' => [
                    [
                        'actions' => [
                            'index',
                            'create',
                            'update',
                            'view',
                            'delete',
                            'content-ordering',
                            'list_content',
                            'search-content',
                            'save-page-setup',
                            'disable',
                            'list-content'
                        ],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                    'disable' => ['POST']
                ],
            ],
        ];
    }

    /**
     * Lists all FrontendContentAssign models.
     * @return mixed
     */
    public function actionIndex() {
        $page_id = filter_var($_GET['FrontendContentAssignSearch']['page_id'], FILTER_SANITIZE_NUMBER_INT);
        $searchModel = new FrontendContentAssignSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $model = new FrontendContentAssign();
        $modelContent = new FrontendContent;
        $modelPage = FrontendPage::findOne($page_id);
        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
                    'model' => $model,
                    'modelContent' => $modelContent,
                    'modelPage' => $modelPage
        ]);
    }

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

    /**
     * Creates a new FrontendContentAssign model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new FrontendContentAssign();
        $query = new Query;
        $query->select('max(content_order) as cOrder')
                ->from('frontend_content_assign')
                ->where(['page_id' => $_GET['page_id']]);
        $row = $query->one();
        $model->content_order = $row['cOrder'] + 1;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index', 'FrontendContentAssignSearch[page_id]' => $_GET['page_id'], 'site_id' => $_GET['site_id'], 'page_name' => $_GET['page_name']]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing FrontendContentAssign 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()) {
            return $this->redirect(['view', 'id' => $model->assign_id, 'site_id' => $_GET['site_id']]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

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

        /* update last update */
        $page = FrontendPage::findOne($res->page_id);
        $page->last_update = PortalDBContent::formatMicrotime();
        $page->save();

        $res->delete();


        return $this->redirect(['index', 'FrontendContentAssignSearch[page_id]' => $_GET['page_id'], 'site_id' => $_GET['site_id'], 'page_name' => $_GET['page_name']]);
    }

    public function actionDisable($id) {
        try {
            $res = $this->findModel($id);
            $res->status = $res->status ? 0 : 1;
            $res->save();

            /* update last update */
            $page = FrontendPage::findOne($res->page_id);
            $page->last_update = PortalDBContent::formatMicrotime();
            $page->save();
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        return $this->redirect(['index', 'FrontendContentAssignSearch[page_id]' => $_GET['page_id'], 'site_id' => $_GET['site_id'], 'page_name' => $_GET['page_name']]);
    }


    /***
     * List content (deprecated)
     * @deprecated Not used anymore for listing the content
     **/
    public function actionList_content($id, $theme_id = 0) {
        $content = FrontendContent::find()->where([
            'category_id' => $id
        ]);

        if (!empty($theme_id)) {
            $content->andWhere([
                'theme_id' => $theme_id
            ]);
        }

        $result = $content->orderBy('content_name ASC')->all();

        $html = '';

        if (!empty($result)) {
            foreach ($result as $c) {
                $html .= "<option value='" . $c->content_id . "'>" . $c->content_name . "</option>";
            }
        } else {
            $html .= "<option>-</option>";
        }

        return $html;
    }

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

    /***
     * content order change
     ***/
    public function actionContentOrdering() {
        $jarr = Yii::$app->request->post('order');
        try {
            $pageid = 0;
            foreach ($jarr as $jkey => $value) {
                $model = FrontendContentAssign::findOne($jkey);
                $model->content_order = $value;
                $model->update();

                $pageid = $model->page_id;
            }

            /* update last update */
            $page = FrontendPage::findOne($pageid);
            $page->last_update = PortalDBContent::formatMicrotime();
            $page->save();
        } catch (\Exception $e) {
            echo 'Caught exception: ', $e->getMessage(), "\n";
        }
    }

    /**
     * return search content function
     *
     * @param int $id
     * @param string $keyword
     * @return void
     */
    public function actionSearchContent(int $id, string $keyword) {
        $contentAssign = \backend\models\frontendcontentassign\FrontendContentAssign::find()->where(['page_id' => $id])->all();
        $resultArr = [];
        foreach ($contentAssign as $content) {
            $result = $this->SearchKeyword($content->content_id, $keyword);
            if (!empty($result)) {
                $resultArr[] = $result;
            }
        }
        return $this->asJson($resultArr);
    }

    /***
     * Save page setup 
     **/
    public function actionSavePageSetup($id, $name, $siteid) {
        $page = FrontendPage::findOne($id);

        if (empty($page)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        if ($page->load(Yii::$app->request->post()) && $page->save()) {
            \Yii::$app->session->setFlash('success', 'Page setup has been saved');
            return $this->redirect(['frontend/frontend-content-assign', 'FrontendContentAssignSearch' => ['page_id' => $id], 'page_name' => $name, 'site_id' => $siteid]);
        }
    }

    /**
     * process the searchkeyword , perform wildcard matching
     *
     * @param integer $contentid
     * @param string $keyword
     * @return array
     */
    private function SearchKeyword(int $contentid, string $keywords): array {
        $frontendcontent = \backend\models\frontendcontent\FrontendContent::find()->where(['content_id' => $contentid])->asArray()->one();
        $contentArr = explode("\n", $frontendcontent['content_details']);
        $match = [];
        for ($i = 0; $i < count($contentArr); $i++) {
            $keyword = preg_quote($keywords, '/');
            if (!empty($keyword)) {
                $pattern = "#{$keyword}#i";
                if (preg_match_all($pattern, $contentArr[$i])) {
                    $match['id'] = $contentid;
                    $match['line'][] = $i + 1;
                }
            }
        }
        return $match;
    }

    public function actionListContent($query, $page=1) {
        $page = $page - 1;
        $limit = 10;
        $record = FrontendContent::find()
                    ->andFilterWhere(['like', 'content_name', $query]);
        
        $content = $record->limit($limit)
                    ->offset($limit * $page)
                    ->all();
        
        $count   = $record->count();

        $data = [];

        array_walk($content, function($arr, $index) use(&$data, $page, $limit){
            $serial = ($limit * ($page)) + ($index + 1);
            $data['items'][$index]['id']   = $arr['content_id'];
            $data['items'][$index]['serial']   = $serial;
            $data['items'][$index]['content_name']     = $arr->content_name;
            $data['items'][$index]['content_type']     = $arr->content_is_php ? 'PHP' : 'HTML';
            $data['items'][$index]['content_theme']    = $arr->theme->title ?? '-';
            $data['items'][$index]['content_category'] = $arr->category->category_name ?? '-';
        });
        
        $data['total_count'] = $count;
        
        $this->asJson($data);
    }

}