<?php
namespace install\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use install\models\InstallForm;
use install\models\CreateManagerForm;
use common\models\Config;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public function init(){
        $this->enableCsrfValidation = false;
    }
    

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        if(file_exists(ROOT_PATH.'data/install.lock')){
            exit('The application has been installed.');
        }
        return $this->render('index');
    }
    public function actionStep1(){
        if(file_exists(ROOT_PATH.'data/install.lock')){
            exit('The application has been installed.');
        }
        $frameworkPath = Yii::$app->basePath . '/../vendor/yiisoft/yii2';
        require_once($frameworkPath . '/requirements/YiiRequirementChecker.php');
        $requirementsChecker = new \YiiRequirementChecker();
        
        $gdMemo = $imagickMemo = 'Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required for image CAPTCHA.';
        $gdOK = $imagickOK = false;

        if (extension_loaded('imagick')) {
            $imagick = new Imagick();
            $imagickFormats = $imagick->queryFormats('PNG');
            if (in_array('PNG', $imagickFormats)) {
                $imagickOK = true;
            } else {
                $imagickMemo = 'Imagick extension should be installed with PNG support in order to be used for image CAPTCHA.';
            }
        }

        if (extension_loaded('gd')) {
            $gdInfo = gd_info();
            if (!empty($gdInfo['FreeType Support'])) {
                $gdOK = true;
            } else {
                $gdMemo = 'GD extension should be installed with FreeType support in order to be used for image CAPTCHA.';
            }
        }
        $requirements = array(
            array(
                'name' => 'PDO extension',
                'mandatory' => true,
                'condition' => extension_loaded('pdo'),
                'memo' => 'Required for All DB-related classes.',
            ),
            array(
                'name' => 'PDO MySQL extension',
                'mandatory' => false,
                'condition' => extension_loaded('pdo_mysql'),
                'memo' => 'Required for MySQL database.',
            ),
            // CAPTCHA:
            array(
                'name' => 'GD PHP extension with FreeType support',
                'mandatory' => false,
                'condition' => $gdOK,
                'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html">Captcha</a>',
                'memo' => $gdMemo,
            ),
            array(
                'name' => 'ImageMagick PHP extension with PNG support',
                'mandatory' => false,
                'condition' => $imagickOK,
                'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html">Captcha</a>',
                'memo' => $imagickMemo,
            ),
            // PHP ini :
            'phpExposePhp' => array(
                'name' => 'Expose PHP',
                'mandatory' => false,
                'condition' => $requirementsChecker->checkPhpIniOff("expose_php"),
                'by' => 'Security reasons',
                'memo' => '"expose_php" should be disabled at php.ini',
            ),
            'phpAllowUrlInclude' => array(
                'name' => 'PHP allow url include',
                'mandatory' => false,
                'condition' => $requirementsChecker->checkPhpIniOff("allow_url_include"),
                'by' => 'Security reasons',
                'memo' => '"allow_url_include" should be disabled at php.ini',
            ),
        );
        $system_info = $requirementsChecker->checkYii()->check($requirements)->getResult();
        $need_check_dirs = $this->get_need_check_dirs();
        $dir_check = $this->check_dirs($need_check_dirs);
        return $this->render('step1',[
            'system_info'=>$system_info,
            'dir_check'=>$dir_check,
        ]);
    }
    public function actionStep2(){
        if(file_exists(ROOT_PATH.'data/install.lock')){
            exit('The application has been installed.');
        }
        $model = new InstallForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $check = $model->check_conn();
            if($check['status']==1){
                $model->writeDbinfo();
                return $this->redirect(['step3']);
            }else{
                Yii::$app->session->setFlash('error', $check['msg']);
                return $this->render('step2', [
                    'model' => $model,
                ]);
            }
        } else {
            return $this->render('step2', [
                'model' => $model,
            ]);
        }
    }
    /**
     * 写入基础配置
     */
    protected function write_base_config($data){
        Yii::$app->db->createCommand('UPDATE '.Yii::$app->db->tablePrefix.'config set `value`="'.Yii::$app->request->getHostInfo().'" where `name`="sitedomain"')->execute();
        Yii::$app->db->createCommand('UPDATE '.Yii::$app->db->tablePrefix.'config set `value`="'.trim(Yii::getAlias('@web'),'install').'" where `name`="sitedir"')->execute();
        Yii::$app->db->createCommand('UPDATE '.Yii::$app->db->tablePrefix.'config set `value`="'.$data['CreateManagerForm']['admin_email'].'" where `name`="email"')->execute();
        Config::updateCache();
    }
    public function actionStep3(){
        if(file_exists(ROOT_PATH.'data/install.lock')){
            exit('The application has been installed.');
        }
        $model = new CreateManagerForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $folder = Yii::$app->basePath.'/migrations/sql';
            $list = scandir($folder);
            foreach ($list as $key => $value) {
                if($value!='.' && $value!='..'){
                    $this->_restoreData($folder.'/'.$value);
                }
            }
            $createResult = $model->createManager();
            if($createResult['status']==1){
                $this->write_base_config(Yii::$app->request->post());
                file_put_contents(ROOT_PATH.'data/install.lock','');
                return $this->redirect(['finish']);
            }else{
                Yii::$app->session->setFlash('error', $createResult['msg']);
                return $this->refresh();
            }
        } else {
            return $this->render('step3', [
                'model' => $model,
            ]);
        }
    }
    public function actionFinish(){
        $frontend_url = Yii::$app->params['sitedomain'].Yii::$app->params['sitedir'];
        $backend_url = Yii::$app->params['sitedomain'].Yii::$app->params['sitedir'].'admin';
        return $this->render('finish',[
            'frontend_url'=>$frontend_url,
            'backend_url'=>$backend_url,
        ]);
    }
    protected function get_need_check_dirs(){
        return array(
            'assets',
            'runtime',
            'install',
            'install/assets',
            'admin',
            'admin/assets',
            'data',
            'data/scws',
            'data/upload',
            'protected/install/runtime',
            'protected/backend/runtime',
            'protected/backend/migrations',
            'protected/frontend/runtime',
            'protected/frontend/config/route-rule.php',
            'protected/common/config/config.php',
            'protected/common/config/db.php',
            );
    }
    protected function check_dirs($dirs)
    {
        $checked_dirs = array();
        $s = 0;
        foreach ($dirs AS $k=> $dir)
        {
            $checked_dirs[$k]['dir'] = $dir;
            if (!file_exists(ROOT_PATH.$dir))
            {
                $checked_dirs[$k]['read_status'] = 'success';
                $checked_dirs[$k]['write_status'] = 'success';
                $checked_dirs[$k]['read'] = '<span style="color:red;">目录不存在</span>';
                $checked_dirs[$k]['write'] = '<span style="color:red;">目录不存在</span>';
                !$s && $s = 1;
            }
            else
            {       
            if (is_readable(ROOT_PATH.$dir))
            {
                $checked_dirs[$k]['read_status'] = 'success';
                $checked_dirs[$k]['read'] = '√可读';
            }else{
                $checked_dirs[$k]['read_status'] = 'danger';
                $checked_dirs[$k]['read'] = '×不可读';
                !$s && $s = 1;
            }
            if(is_writable(ROOT_PATH.$dir)){
                $checked_dirs[$k]['write_status'] = 'success';
                $checked_dirs[$k]['write'] = '√可写';
            }else{
                $checked_dirs[$k]['write_status'] = 'danger';
                $checked_dirs[$k]['write'] = '×不可写';
                !$s && $s = 1;
            }
            }
        }
        return $checked_dirs;
    }
    public function _restoreData($file){
        require $file;
        $class_name = '\\'.$this->_getClassNameByFile($file);
        $class_name = trim($class_name,'.php');
        $class = new $class_name;
        $class->down();
        $class->up();
        unset($class);
        return true;
    }
    /**
     * 根据文件名获取备份数据类名
     */
    protected function _getClassNameByFile($path){
        return basename($path);
    }
}
