<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/3/10
 * Time: 下午9:08
 */
class fcgi_server
{
    static private $stInstance = NULL;

    static public function instance()
    {
        if(self::$stInstance == NULL) {
            self::$stInstance = new fcgi_server();
        }
        return self::$stInstance;
    }

    private function is_exclude($file)
    {
        static $exfiles = array('wxnotify.php','pub_wxnotify.php','alipay_notify_url.php','dispatch_notify.php','kdniao_notify.php',
            'cmbpay_notify.php','cmbpay_sign.php','wxauthor.php','api/wxLogin/index.php','api/wxLogin/callback.php',
            'test.php');

        $path = BASE_ROOT_PATH . '/mobile/';
        $file = str_replace($path,'',$file);

        return in_array($file,$exfiles);
    }

    private function parase_requri()
    {
        $method = strtolower(request_helper::method());
        if($method == 'get') {
            return;
        }

        $file = request_helper::req_uri();
        $ops = explode("?",$file);
        if(count($ops) == 2)
        {
            $squery = $ops[1];
            $params = preg_split('/&|=/', $squery);

            for ($i = 0; $i < count($params); ++$i) {
                $key = $params[$i];
                $val = $params[++$i];
                $_GET[$key] = $val;
                $_POST[$key] = $val;
            }
        }
    }

//    private function do_clear($ar)
//    {
//        if(isset($ar) && is_array($ar))
//        {
//            foreach($ar as $key=>$value) {
//                unset($ar[$key]);
//            }
//
//        }
//    }

    private function clear_global()
    {
        $_SESSION = [];
        $_COOKIE = [];
        $_POST = [];
        $_GET = [];

//        $this->do_clear($_SESSION);
//        $this->do_clear($_COOKIE);
//        $this->do_clear($_POST);
//        $this->do_clear($_GET);
    }

    public function run_looper()
    {
        DFAFilter::instance();
        require_once(BASE_ROOT_PATH.'/mobile/index.php');

        while(($ret = fcgi_accept()) >= 0)
        {
            $start = microtime(true);

            ob_start();
            $this->clear_global();
            performance_helper::clear();
            http_header::instance()->start();

            try
            {
                Log::start_sql_log();
                $this->parase_requri();
                init_request();
                init_cookie($_SERVER['HTTP_COOKIE']);

                session::instance()->start();
                $file = request_helper::script_file();
                $remote_addr = request_helper::remote_addr();
                Log::record("file={$file} remoteaddr={$remote_addr}",Log::DEBUG);
                if(file_exists($file))
                {
                    if(self::is_exclude($file))
                    {
                        include $file;
                    }
                    else
                    {
                        fcgi_header("Content-Type: text/html; charset=UTF-8");

                        if(!isset($_GET['act'])) {
                            $_GET['act'] = 'index';
                        }
                        if(!isset($_GET['op'])) {
                            $_GET['op'] = 'index';
                        }
                        if(!isset($_POST['act'])) {
                            $_POST['act'] = 'index';
                        }
                        if(!isset($_POST['op'])) {
                            $_POST['op'] = 'index';
                        }
                        Base::mobile_control();
                    }
                }
                else
                {
                    fcgi_header("Content-Type: text/html; charset=UTF-8");
                    echo "no such file.";
                }
            }
            catch (Exception $ex) {
                mobileControl::outerr($ex->getCode(),$ex->getMessage());
                Log::record("run_looper exception catch code={$ex->getCode()} msg={$ex->getMessage()}",Log::ERR);
            }
            session::instance()->end();
            fcgi_headers_sent();
            $contents = ob_get_clean();
            fcgi_echo($contents);

            //fcgi_finish();//单线程的情况下不需要调用
            $msg = sprintf("request time=%.6f\r\n\r\n",microtime(true) - $start);
            Log::record($msg,Log::DEBUG);
        }

        fcgi_fini();
    }
}
