Your IP : 216.73.217.154


Current Path : /var/www/html/jkdm/backend/modules/admin/controllers/
Upload File :
Current File : /var/www/html/jkdm/backend/modules/admin/controllers/DataExportController.php

<?php

namespace backend\modules\admin\controllers;

use Yii;
use backend\modules\admin\models\DataExport;
use backend\modules\admin\models\DataExportSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * DataExportController implements the CRUD actions for DataExport model.
 */
class DataExportController extends Controller
{   

    public static $blacklist = [
        'DELETE',
        'DROP',
        'ALTER',
        'INSERT',
        'UPDATE',
        'RENAME',
        'TRUNCATE',
        'CREATE',
        'DESCRIBE',
        'EXPLAIN',
        'SET',
        'SHOW',
        'GRANT',
        'REVOKE',
        'CALL',
        'HANDLER',
        'LOAD',
        'REPLACE',
        'DO',
        'WITH',
        'IMPORT',
        'LOCK',
        'BEGIN',
        'END',
        'DECLARE',
        'UPDATETEXT',
        'WRITETEXT',
        'READTEXT',
        'MERGE'
    ];

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

    /**
     * Lists all DataExport models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DataExportSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

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

    /**
     * Creates a new DataExport model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new DataExport();

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

            /* roles */
            $roles = implode(',',$model->roles);
            $model->roles = $roles;

            /* set column name */

            if ( isset($model->is_sql) && $model->is_sql == 0 ) {
                $model->column_name = implode(",", $_POST['column_name']);
            } else {
                $filter = self::sqlfilter($model->SQL);
                if (count($filter) > 0) {
                    $blacklist = implode('|', self::$blacklist);
                    Yii::$app->session->setFlash('error', 'RALAT : SQL yang digunakan tidak dibenarkan');
                    return $this->render('create', [
                        'model' => $model,
                    ]);
                }

                /* check the queries for errors */
                try {
                    $connection = Yii::$app->getDb();
                    $command = $connection->createCommand($model->SQL);
                    $rows = $command->queryAll();
                } catch (yii\db\Exception $e) {
                    Yii::$app->session->setFlash('error', 'RALAT :- ' . $e->errorInfo[2]);
                    return $this->render('create', [
                        'model' => $model,
                    ]);
                }

            }

            $model->save();
            
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing DataExport 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()) ) {
            
            /* roles */
            $roles = implode(',', $model->roles);
            $model->roles = $roles;

            /* set column name */
            if (isset($_POST['DataExport']['is_sql']) && $_POST['DataExport']['is_sql'] == 0) {
                $model->column_name = implode(",", $_POST['column_name']);
            } else {
                $filter = self::sqlfilter($model->SQL);
                if (count($filter) > 0) {
                    $blacklist = implode('|', self::$blacklist);
                    Yii::$app->session->setFlash('error', 'RALAT : SQL yang digunakan tidak dibenarkan');
                    return $this->render('update', [
                        'model' => $model,
                    ]);
                }

                try {
                    $connection = Yii::$app->getDb();
                    $command = $connection->createCommand($model->SQL);
                    $rows = $command->queryAll();
                } catch (yii\db\Exception $e) {
                    Yii::$app->session->setFlash('error', 'RALAT :- ' . $e->errorInfo[2] );
                    return $this->render('update', [
                        'model' => $model,
                    ]);
                }

            }

            $model->save();

            return $this->redirect(['index']);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

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

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

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

    public function actionGetFieldName(string $table)
    {       
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $db_connection = Yii::$app->db;
        $dbSchema = $db_connection->schema;
        $tables = $dbSchema->getTableSchema($table);
        $columns = [];
        // echo '<pre>'; var_dump($tables->columns); echo '</pre>';die();
        foreach($tables->columns as $column)
        {
            $columns[] = $column->name;
        }

        return $columns;
    }

    public function actionExport($id){
        $dataEx = DataExport::findOne($id);
        
        /* set header */
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="'. preg_replace('/\W+/','',$dataEx->title) .'.csv"');

        if( $dataEx->is_sql == 0 ){
            
            $columns = explode(",",$dataEx->column_name);
            $table  = $dataEx->table_name;

            $rows = (new \yii\db\Query())
                    ->select($columns)
                    ->from($table)
                    ->all();
            
            $fp = fopen('php://output', 'wb');
            
            /* first column name */
            fputcsv($fp, $columns);

            foreach ($rows as $row) {
                fputcsv($fp, $row);
            }
            
            fclose($fp);

        }elseif($dataEx->is_sql == 1 ){

            $connection = Yii::$app->getDb();
            $command = $connection->createCommand($dataEx->SQL);
            $rows = $command->queryAll();
            
            $fp = fopen('php://output', 'wb');
            $rkey = $rows[0] ?? [];
            $rkey = array_keys($rkey);

            /* first column name */
            fputcsv($fp, $rkey);
            
            foreach ($rows as $row) {
                fputcsv($fp, $row);
            }

            fclose($fp);
        }

        die;
    }

    /**
     * Filter sql for matches in blacklist words
     *
     * @return array
     */
    public static function sqlfilter($sql): array{
        $blacklist = self::$blacklist;

        /* loop trough boundaries */
        foreach ($blacklist as $word) {
            $boundaries[] = "\b{$word}\b";
        }

        /* prepare regex */
        $words = "/" . implode("|", $boundaries) . "/i";
        preg_match_all($words, $sql, $matches, PREG_OFFSET_CAPTURE);

        return $matches[0];
    }
}