<?php
/*
+--------------------------------------------------------------------------
|   TanyaCMS - Question and Answer Sofware
|   -----------------------------------------------------------------------
|   by fbschool dev team
|   (c) 2011 - 2012 FBSCHOOL
|   http://www.fbschool.com/tanyacms
|   -----------------------------------------------------------------------
|   This is NOT a freeware, use is subject to license terms
|   Support: 13455n@gmail.com
+--------------------------------------------------------------------------
*/

class ASK_APP
{
	private static $config;
	private static $db;
	private static $form;
	private static $upload;
	private static $image;
	private static $pagination;
	private static $cache;
	
	private static $models = array();
	private static $plugins = array();
	private static $setting = array();
	
	public static $_debug = array();
	
	/**
	 * Program begins execution, find controller and action
	 * 
	 * @param string $app_dir Application of the absolute directory if not, is the current directory
	*/
	public static function run()
	{
		// Global Variables
		global $__controller, $__action, $__default_controller, $__default_action;
		
		self::init();
		
		if (!$app_dir = load_class('core_uri')->set_rewrite()->app_dir)
		{
			$app_dir = ROOT_PATH . 'app/home/';
		}
		
		// Controller operation is selected
		if (! $__controller)
		{
			if (isset($_GET['c']))
			{
				$__controller = $_GET['c']; // There is an incoming controller field name
			}
			else
			{
				$__controller = $__default_controller ? $__default_controller : 'main'; // Reads the default field name controllers
			}
		}
		
		if (! $__action)
		{
			// Action		
			if (isset($_GET['act']))
			{
				$__action = $_GET['act']; // There is an incoming action field name
			}
			else
			{
				$__action = $__default_action ? $__default_action : 'act'; // Read the default action field name
			}
		}

		// Incoming application directory, the return path controller
		
		$handle_controller = self::create_controller($__controller, $app_dir);
		
		$action_method = $__action . '_action';
		
		// Judge
		if (! is_object($handle_controller) || ! method_exists($handle_controller, $action_method))
		{
			HTTP::error_404();
		}
		
		// Judge ACTION
		if (method_exists($handle_controller, 'get_access_rule'))
		{
			$access_rule = $handle_controller->get_access_rule();
		}
		
		// Use white list or blacklist judgment, the default blacklist
		if ($access_rule)
		{			
			// Blacklist, blacklist check  'white' white list, outside the whitelist check(The default is to check the blacklist)
			if (isset($access_rule['rule_type']) && ($access_rule['rule_type'] == 'white')) // White
			{
				if ((! $access_rule['actions']) || (! in_array($__action, $access_rule['actions'])))
				{
					self::login_check();
				}
			}
			else if (isset($access_rule['actions']) && in_array($__action, $access_rule['actions'])) // Non-white is black
			{
				self::login_check();
			}
		
		}
		else // Not set on all checks
		{
			self::login_check();
		}
		
		// Execution
		$handle_controller->$action_method();
	}

	private static function init()
	{		
		self::$config = load_class('core_config');
		self::$db = load_class('core_db');
		self::$plugins = load_class('core_plugins');
		self::$setting = self::model('setting')->get_setting();
		
		if (get_setting('default_timezone'))
		{
			date_default_timezone_set(get_setting('default_timezone'));
		}

		$img_url = get_setting('img_url');
		
		$base_url = get_setting('base_url');
		
		! empty($img_url) ? define('GET_STATIC_URL', $img_url) : define('GET_STATIC_URL', $base_url . '/static');
		
		
		if (ASK_APP::config()->get('system')->debug)
		{
			$corn_log_file = TEMP_PATH . 'corn_log.php';
		
			if (file_exists($corn_log_file))
			{
				$corn_log = unserialize(file_get_contents($corn_log_file));
			}
			
			if (is_array($corn_log))
			{
				foreach ($corn_log AS $cornd_tag => $run_time)
				{
					ASK_APP::debug_log('cronlog', 0, 'Tag: ' . $cornd_tag . ', Last run time: ' . date('Y-m-d H:i:s', $run_time));
				}
			}
		}
	}
	
	public static function setting()
	{
		if (!self::$setting)
		{
			return false;
		}
		
		return self::$setting;
	}

	/**
	 * Establish controller
	 * Back to the controller class object
	 * @param string $route
	 */
	public static function create_controller($controller, $app_dir)
	{
		if (trim($app_dir) == '')
		{
			return false; // No application directory, an error is returned
		}
		
		if (($controller = trim($controller, '/')) === '')
		{
			$controller = 'main';
		}
		
		$class_file = $app_dir . $controller . '.php';
		
		if (is_file($class_file))
		{
			if (! class_exists($controller, false))
			{
				require_once ($class_file);
			}
			
			if (class_exists($controller, false))
			{
				return new $controller();
			}
		}
		
		return false;
	}

	
	/**
   	* Format pop-up message component return value
   	* 
   	* @param $rsm 		Result data can be empty
   	* @param $errno		Error code, the default is 0 no error, the other is the corresponding error code
   	* @param $err		Error Messages
   	* @param $level 	Error level, the default is 0, $err Will be directly displayed to the user, if one is not displayed to the user, is suggestive of a unified  System is busy, please try again later...
   	* @param $log		When the data layer component management center needs to write the log when values are given, the default is empty, do not write the log
   	* 
   	* @return Return to standard RSM data
   	*/
	public static function RSM($rsm, $errno = 0, $err = "", $level = 0, $log = "")
	{
		return array(
			'rsm' => $rsm, 
			'errno' => (int)$errno, 
			'err' => $err, 
			'level' => $level, 
			'log' => $log
		);
	}
		
	public static function login_check()
	{
		if (! USER::isuser_login())
		{
			HTTP::redirect('/account/login/url-' . base64_encode($_SERVER['REQUEST_URI']));
		}
	}

	public static function config()
	{
		return self::$config;
	}
	
	public static function upload()
	{
		if (!self::$upload)
		{
			self::$upload = load_class('core_upload');
		}
		
		return self::$upload;
	}
	
	public static function image()
	{
		if (!self::$image)
		{
			self::$image = load_class('core_image');
		}
		
		return self::$image;
	}
	
	public static function cache()
	{
		if (!self::$cache)
		{
			self::$cache = load_class('core_cache');
		}
		
		return self::$cache;
	}
		
	public static function form()
	{
		if (!self::$form)
		{
			self::$form = load_class('core_form');
		}
		
		return self::$form;
	}
	
	public static function plugins()
	{
		return self::$plugins;
	}
	
	public static function pagination()
	{
		if (!self::$pagination)
		{
			self::$pagination = load_class('core_pagination');
		}
		
		return self::$pagination;
	}
	
	public static function db($db_object_name = 'master')
	{
		if (!self::$db)
		{
			return false;
		}
		
		return self::$db->setObject($db_object_name);
	}
	
	public static function debug_log($type, $expend_time, $message)
	{
		self::$_debug[$type][] = array(
			'expend_time' => $expend_time,
			'log_time' => microtime(true),
			'message' => $message
		);
	}

	public static function model($model_class = null)
	{
		if (!$model_class)
		{
			$model_class = 'ASK_MODEL';
		}
		else if (! strstr($model_class, '_class'))
		{
			$model_class .= '_class';
		}
		
		if (! isset(self::$models[$model_class]))
		{
			$model = new $model_class();
			self::$models[$model_class] = $model;
		}
		
		return self::$models[$model_class];
	}
}