<?php
$include_path = ini_get('include_path');
$include_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'flatframe' . PATH_SEPARATOR . $include_path;
ini_set('include_path', $include_path);
unset($include_path);
require_once ('spyc/spyc.php');
class flatframe {
    var $version = '0.12';
    var $notice = '本プログラムは econosys system の著作物です。著作者の許可無き改変、別システムでの使用を禁止します。copyright (c) econosys system http://econosys.jp/system/ ';
    var $template;
    var $dsn;
    var $db;
    var $timer;
    var $q;
    var $cmd;
    var $rootdir = '.';
    var $run_modes = array();
    var $_ff_config;
    var $_ff_configfile = '';
    var $validator = null;
    var $_ff_validator_config;
    var $_ff_validator_configfile = 'validator.yml';
    function _framework_setup_config() {
        if (file_exists("$this->rootdir/$this->_ff_configfile")) {
            $this->_ff_config = Spyc::YAMLLoad("$this->rootdir/$this->_ff_configfile");
        } else {
            die("can't open configfile '$this->rootdir/$this->_ff_configfile'");
        }
        if (isset($this->_ff_config['default_timezone'])) {
            date_default_timezone_set($this->_ff_config['default_timezone']);
        } else {
            date_default_timezone_set('Asia/Tokyo');
        }
    }
    function _framework_setup_mbstring() {
        mb_language("ja");
        if (isset($this->_ff_config['script_encoding'])) {
            mb_internal_encoding($this->_ff_config['script_encoding']);
            ini_set('mbstring.internal_encoding', $this->_ff_config['script_encoding']);
            ini_set('mbstring.script_encoding', $this->_ff_config['script_encoding']);
        }
    }
    function _framework_setup_httpheader() {
        if (isset($this->_ff_config['httpheader_encoding'])) {
            ini_set('default_charset', $this->_ff_config['httpheader_encoding']);
        }
    }
    function _framework_setup_template() {
        require_once ('Smarty/Smarty.class.php');
        $this->template = new Smarty();
        $this->template->template_dir = $this->rootdir . "/templates/";
        $this->template->compile_dir = $this->rootdir . "/templates_c/";
        if (is_dir($this->rootdir . "/plugins/")) {
            array_push($this->template->plugins_dir, $this->rootdir . "/plugins/");
        }
        $this->template->autoload_filters = array();
        if (isset($this->_ff_config['prefilter'])) {
            if (!isset($this->template->autoload_filters['pre'])) {
                $this->template->autoload_filters['pre'] = array();
            }
            array_push($this->template->autoload_filters['pre'], $this->_ff_config['prefilter']);
        }
        if (isset($this->_ff_config['postfilter'])) {
            if (!isset($this->template->autoload_filters['post'])) {
                $this->template->autoload_filters['post'] = array();
            }
            array_push($this->template->autoload_filters['post'], $this->_ff_config['postfilter']);
        }
        if (isset($this->_ff_config['outputfilter'])) {
            if (!isset($this->template->autoload_filters['output'])) {
                $this->template->autoload_filters['output'] = array();
            }
            array_push($this->template->autoload_filters['output'], $this->_ff_config['outputfilter']);
        }
        if (isset($this->_ff_config['smarty_force_compile'])) {
            $this->template->force_compile = $this->_ff_config['smarty_force_compile'];
        }
        if (isset($this->_ff_config['smarty_compile_check'])) {
            $this->template->compile_check = $this->_ff_config['smarty_compile_check'];
        }
    }
    function stop_smarty_filter($filter = '') {
        if ($filter == '') {
            return false;
        } elseif ($filter == 'outputfilter') {
            unset($this->template->autoload_filters['output']);
        } elseif ($filter == 'postfilter') {
            unset($this->template->autoload_filters['post']);
        } elseif ($filter == 'prefilter') {
            unset($this->template->autoload_filters['pre']);
        }
    }
    function exec_smarty_filter($filter = '', $html) {
        if ($filter == '') {
            return $html;
        } else {
            require_once ($this->rootdir . '/plugins/' . "{$filter}.{$this->_ff_config[$filter]}.php");
            $html = call_user_func("smarty_{$filter}_{$this->_ff_config[$filter]}", $html, '');
            return $html;
        }
    }
    function _framework_setup_form() {
        if (isset($_SERVER['SERVER_PORT'])) {
            if ($_SERVER['SERVER_PORT'] == 443) {
                $protocol = 'https://';
            } else {
                $protocol = 'http://';
            }
            $this->q['_program_name'] = $_SERVER['PHP_SELF'];
            $this->q['_program_uri'] = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        }
        $this->q['_template_dir'] = $this->rootdir . '/templates';
        $cmd = '';
        if (getenv("REQUEST_METHOD") == 'GET') {
            foreach ($_GET as $key => $value) {
                if (is_array($value)) {
                    $array = array();
                    foreach ($value as $k => $v) {
                        if (get_magic_quotes_gpc() == 1) {
                            $v = stripslashes($v);
                            array_push($array, $v);
                        } else {
                            array_push($array, $v);
                        }
                    }
                    $value = $array;
                } else if (get_magic_quotes_gpc() == 1) {
                    $value = stripslashes($value);
                }
                $this->q[$key] = $value;
            }
            if (isset($_GET['cmd'])) {
                $this->cmd = $_GET['cmd'];
            }
        } else if (getenv("REQUEST_METHOD") == 'POST') {
            foreach ($_POST as $key => $value) {
                if (is_array($value)) {
                    $array = array();
                    foreach ($value as $k => $v) {
                        if (get_magic_quotes_gpc() == 1) {
                            $v = stripslashes($v);
                            array_push($array, $v);
                        } else {
                            array_push($array, $v);
                        }
                    }
                    $value = $array;
                } else if (get_magic_quotes_gpc() == 1) {
                    $value = stripslashes($value);
                }
                $this->q[$key] = $value;
            }
            if (isset($_POST['cmd'])) {
                $this->cmd = $_POST['cmd'];
            }
        }
        if (@$this->_ff_config['use_path_info'] == 1) {
            $this->_get_path_info();
        }
        $this->convert_form($this->_ff_config['script_encoding'], $this->_ff_config['output_encoding']);
    }
    function _get_path_info() {
        if (!isset($_SERVER['PATH_INFO'])) {
            if ($_SERVER['SCRIPT_NAME'] == $_SERVER['REQUEST_URI']) {
                return;
            } elseif (isset($_SERVER['QUERY_STRING'])) {
                return;
            } else {
                print 'can not get PATH_INFO';
                return;
            }
        } else {
            $pi = preg_replace("{^/}", "", $_SERVER['PATH_INFO']);
            $a = preg_split("{/}", $pi);
            $this->cmd = array_shift($a);
            $this->q['cmd'] = $this->cmd;
            $this->q['path_info_arg'] = $a;
            $this->q['_program_name'] = preg_replace("{{$_SERVER['PATH_INFO']}}", "", $this->q['_program_name']);
            $this->q['_program_uri'] = preg_replace("{{$_SERVER['PATH_INFO']}}", "", $this->q['_program_uri']);
        }
    }
    function _OLD__framework_setup_form_OLD() {
        if (isset($_SERVER['SERVER_PORT'])) {
            if ($_SERVER['SERVER_PORT'] == 443) {
                $protocol = 'https://';
            } else {
                $protocol = 'http://';
            }
            $this->q['_program_name'] = $_SERVER['PHP_SELF'];
            $this->q['_program_uri'] = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        }
        $this->q['_template_dir'] = $this->rootdir . '/templates';
        $cmd = '';
        $env_request_method = getenv("REQUEST_METHOD");
        if (strcmp($env_request_method, '') == 0) {
            $env_request_method = $_SERVER['REQUEST_METHOD'];
        }
        if ($env_request_method == 'GET') {
            foreach ($_GET as $key => $value) {
                if (is_array($value)) {
                    $array = array();
                    foreach ($value as $k => $v) {
                        if (get_magic_quotes_gpc() == 1) {
                            $v = stripslashes($v);
                            array_push($array, $v);
                        } else {
                            array_push($array, $v);
                        }
                    }
                    $value = $array;
                } else if (get_magic_quotes_gpc() == 1) {
                    $value = stripslashes($value);
                }
                $this->q[$key] = $value;
            }
            if (isset($_GET['cmd'])) {
                $this->cmd = $_GET['cmd'];
            }
        } else if ($env_request_method == 'POST') {
            foreach ($_POST as $key => $value) {
                if (is_array($value)) {
                    $array = array();
                    foreach ($value as $k => $v) {
                        if (get_magic_quotes_gpc() == 1) {
                            $v = stripslashes($v);
                            array_push($array, $v);
                        } else {
                            array_push($array, $v);
                        }
                    }
                    $value = $array;
                } else if (get_magic_quotes_gpc() == 1) {
                    $value = stripslashes($value);
                }
                $this->q[$key] = $value;
            }
            if (isset($_POST['cmd'])) {
                $this->cmd = $_POST['cmd'];
            }
        }
        $this->convert_form($this->_ff_config['script_encoding'], $this->_ff_config['output_encoding']);
    }
    function convert_form($encoding_to, $encoding_from) {
        if (isset($this->_ff_config['script_encoding'])) {
            $encoding_to = $this->_ff_config['script_encoding'];
        }
        if (isset($this->_ff_config['output_encoding'])) {
            $encoding_from = $this->_ff_config['output_encoding'];
        }
        if (isset($this->_ff_config['httpheader_encoding'])) {
            $encoding_from = $this->_ff_config['httpheader_encoding'];
        }
        if (!isset($encoding_to)) {
            die("argument 'encoding_to' is not given.(please check constractor)");
        }
        foreach ($this->q as $key => $value) {
            if (is_array($value)) {
            } else {
                $this->q[$key] = mb_convert_encoding($value, $encoding_to, $encoding_from);
            }
        }
    }
    function _framework_validator_config() {
        if (file_exists("$this->rootdir/$this->_ff_validator_configfile")) {
            $this->validator = new validator("$this->rootdir/$this->_ff_validator_configfile", $this->q);
        }
    }
    function dump($data) {
        print "\n" . '<pre style="text-align:left;">' . "\n";
        print_r($data);
        print "</pre>\n\n";
    }
    function dump2($data) {
        print "\n" . '<!-- <pre style="text-align:left;">' . "\n";
        print_r($data);
        print "</pre> --> \n\n";
    }
    function dumpmem() {
        print "\n" . '<pre style="text-align:left;">' . "\n";
        $mem = memory_get_usage();
        $mem = number_format($mem);
        print ("Memory:{$mem}");
        print "</pre>\n\n";
    }
    function dumpmem2() {
        print "\n<!-- ";
        $mem = memory_get_usage();
        $mem = number_format($mem);
        print ("Memory:{$mem}");
        print " -->\n";
    }
    function make_hidden($hash = array()) {
        if (count($hash) == 0) {
            $hash = $this->q;
        }
        $hidden = '';
        foreach ($hash as $k => $v) {
            if (preg_match('/^_/', $k)) {
            } else if ($k == 'cmd') {
            } else if ($k == 'hidden') {
            } else if (is_array($v)) {
                foreach ($v as $kk => $vv) {
                    $vv = htmlspecialchars($vv, ENT_QUOTES, 'ISO-8859-1');
                    $hidden.= '<input type="hidden" name="' . $k . '[]" value="' . $vv . '" />' . "\n";
                }
            } else {
                $v = htmlspecialchars($v, ENT_QUOTES, 'ISO-8859-1');
                $hidden.= '<input type="hidden" name="' . $k . '" value="' . $v . '" />' . "\n";
            }
        }
        return $hidden;
    }
    function _framework_setup_db() {
        require_once ('DB.php');
        if (isset($this->_ff_config['dbType'])) {
            $this->dsn = $this->_ff_config['dbType'] . "://" . $this->_ff_config['dbUser'] . ":" . $this->_ff_config['dbPass'] . "@" . $this->_ff_config['dbHost'] . "/" . $this->_ff_config['dbName'];
            $this->db = DB::connect($this->dsn);
            if (DB::isError($this->db)) {
                if (isset($this->_ff_config['db_app_db_error'])) {
                    if ($this->_ff_config['db_app_db_error'] == 1) {
                        $exec_method = 'app_db_error';
                        if (method_exists($this, $exec_method)) {
                            call_user_func(array($this, $exec_method));
                        } else {
                            $this->_framework_err("method [$exec_method] is not defined.");
                        }
                        die;
                    }
                }
                $DebugInfo = $this->db->getDebugInfo();
                print "$DebugInfo<br>¥n";
                die($this->db->getMessage());
            }
            if (isset($this->_ff_config['dbDefaultCharacterSet'])) {
                $this->db->query("SET NAMES " . $this->_ff_config['dbDefaultCharacterSet']);
                if (DB::isError($this->db)) {
                    exit($this->db->getMessage());
                }
            }
        }
    }
    function _framework_setup_timer() {
        if (isset($this->_ff_config['timerMode'])) {
            if ($this->_ff_config['timerMode'] == 1) {
                require_once "Benchmark/Timer.php";
                $this->timer = new Benchmark_Timer();
                $this->timer->start();
                $this->timer->setMarker('Start');
            }
        }
    }
    function _framework_setup_error() {
        ini_set('display_errors', "1");
        if (isset($this->_ff_config['errorReporting'])) {
            $pv = floatval(phpversion());
            if ($pv >= 5.3) {
                if ($this->_ff_config['errorReporting'] == 1) {
                    error_reporting(E_ALL & ~E_DEPRECATED);
                } elseif ($this->_ff_config['errorReporting'] == 0) {
                    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
                } elseif ($this->_ff_config['errorReporting'] == - 1) {
                    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);
                }
            } else {
                if ($this->_ff_config['errorReporting'] == 1) {
                    error_reporting(E_ALL);
                } elseif ($this->_ff_config['errorReporting'] == 0) {
                    error_reporting(E_ALL ^ E_NOTICE);
                } elseif ($this->_ff_config['errorReporting'] == - 1) {
                    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
                }
            }
        }
    }
    function do_timer_display() {
        if (isset($this->timer)) {
            $this->timer->stop();
            print '<div align="center">' . "\n";
            $this->timer->display();
            print '</div><br />' . "\n";
        }
    }
    function sanitize_html($mix) {
        if (is_array($mix)) {
            foreach ($mix as $k => $v) {
                if (is_array($v)) {
                    $mix[$k] = $this->sanitize_html($mix[$k]);
                } else {
                    $mix[$k] = htmlspecialchars($mix[$k], ENT_QUOTES);
                }
            }
            return $mix;
        } else {
            return htmlspecialchars($mix[$k], ENT_QUOTES);
        }
    }
    function sanitize_mysql($mix) {
        if (is_array($mix)) {
            foreach ($mix as $k => $v) {
                if (is_array($v)) {
                    $mix[$k] = $this->sanitize_mysql($mix[$k]);
                } else {
                    $mix[$k] = mysql_escape_string($mix[$k]);
                }
            }
            return $mix;
        } else {
            return mysql_escape_string($mix);
        }
    }
    function convert_assign($conv_to, $conv_from, $mix) {
        if (!$conv_to == $conv_from) {
            mb_convert_variables($conv_to, $conv_from, $mix);
        }
        $this->template->assign($mix);
    }
    function convert_encoding_r($mix = '') {
        if ($mix == '') {
            return $mix;
        }
        if (is_array($mix)) {
            foreach ($mix as $k => $v) {
                if (is_array($v)) {
                    $mix[$k] = $this->convert_encoding_r($mix[$k]);
                } else {
                    $mix[$k] = mb_convert_encoding($mix[$k], $this->_ff_config['output_encoding'], $this->_ff_config['script_encoding']);
                }
            }
            return $mix;
        } else {
            return mb_convert_encoding($this->_ff_config['output_encoding'], $this->_ff_config['script_encoding'], $mix);
        }
    }
    function assign($mix) {
        if (isset($this->_ff_config['output_encoding']) && isset($this->_ff_config['script_encoding'])) {
            if (!($this->_ff_config['output_encoding'] == $this->_ff_config['script_encoding'])) {
                $mix = $this->convert_encoding_r($mix);
            }
        }
        $this->template->assign($mix);
    }
    function do_app_prerun() {
        if (method_exists($this, 'app_prerun')) {
            $this->app_prerun();
        }
    }
    function do_app_postrun() {
        if (method_exists($this, 'app_postrun')) {
            $this->app_postrun();
        }
    }
    function do_method() {
        $exec_method = '';
        if (array_key_exists($this->cmd, $this->run_modes)) {
            $exec_method = $this->run_modes[$this->cmd];
        } else if ($this->cmd == '') {
            if (array_key_exists('default', $this->run_modes)) {
                $exec_method = $this->run_modes['default'];
            } else {
                $this->_framework_err("run_modes [default] is not defined.");
            }
        } else {
            $this->_framework_err("run_modes [" . $this->cmd . "] is not defined.");
        }
        if (method_exists($this, $exec_method)) {
            call_user_func(array($this, $exec_method));
        } else {
            $this->_framework_err("method [$exec_method] is not defined.");
        }
    }
    function _framework_err($str) {
        if (isset($this->_ff_config['debugEncoding'])) {
            mb_convert_variables($this->_ff_config['debugEncoding'], 'auto', $str);
        }
        print "=== FRAMEWORK ERROR ========================== <br />\n";
        print "$str <br />\n";
        print "============================================== <br />\n";
        die();
    }
    function print_head() {
        if (isset($this->_ff_config['httpheader_encoding'])) {
            header("Content-Type: text/html; charset={$this->_ff_config['httpheader_encoding']}");
        } else {
            header("Content-Type: text/html;");
        }
    }
    function print_head_nocache() {
        if (isset($this->_ff_config['httpheader_encoding'])) {
            header("Content-Type: text/html; charset={$this->_ff_config['httpheader_encoding']}");
        } else {
            header("Content-Type: text/html;");
        }
        header("Cache-Control: no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
    }
    function _create_loop($loop, $split_no = 2) {
        $new_loop = array();
        $tmp_loop = array();
        $f = 0;
        foreach ($loop as $k => $v) {
            if ($f < ($split_no - 1)) {
                array_push($tmp_loop, $v);
            } elseif ($f == ($split_no - 1)) {
                array_push($tmp_loop, $v);
                array_push($new_loop, $tmp_loop);
                $tmp_loop = array();
                $f = 0;
                continue;
            }
            $f++;
        }
        if (count($tmp_loop) > 0) {
            array_push($new_loop, $tmp_loop);
        }
        return $new_loop;
    }
    function run() {
        $this->setup();
        $this->_framework_setup_config();
        $this->_framework_setup_mbstring();
        $this->_framework_setup_httpheader();
        $this->_framework_setup_form();
        $this->_framework_setup_template();
        if (!isset($this->_ff_config['dbAutoConnect'])) {
            $this->_framework_setup_db();
        } elseif ($this->_ff_config['dbAutoConnect'] == false) {
        } else {
            $this->_framework_setup_db();
        }
        $this->_framework_setup_timer();
        $this->_framework_setup_error();
        $this->do_app_prerun();
        $this->do_method();
        $this->do_app_postrun();
        $this->do_timer_display();
    }
} ?>