<?php
class Basic_Router
{
	var $module_config = array();

	var $class  = '';
	var $method = '';

	var $uri_string = NULL;
	var $segments   = array();
	var $args       = array();

	var $default_controller  = 'index';
	var $default_method      = 'index';
//	var $permitted_uri_chars = 'a-z 0-9~%.:_-';
	var $permitted_uri_chars = 'a-z 0-9~%\.\:_\-';

	/**
	 * Constructor
	 */
	function __construct()
	{
	}

	function _set_module_config()
	{
		$module_handler =& xoops_gethandler('module') ;
		$xoopsModule = $module_handler->getByDirname($this->mydirname) ;
		$config_handler =& xoops_gethandler('config') ;
		$this->module_config =& $config_handler->getConfigsByCat(0, $xoopsModule->getVar('mid'));
	}

	// --------------------------------------------------------------------
	function _set_routing()
	{
		if ($this->module_config['url_approach'] == 0) {

			//Query Approach
			if (!isset($_GET['c'])) {
				$_GET['c'] = $this->default_controller;
			}
			$this->_add_CM_in_query();
			$controller = isset($_GET['c']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', strtolower($_GET['c'])): $this->default_controller;
			$method = isset($_GET['m']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', strtolower($_GET['m'])): $this->default_method;

			$this->_set_request(array($controller, $method));
			$this->get_query = TRUE;
			$this->_check_args();

		} else {

			//Segment Approach
			$this->_fetch_uri_string();

			if ($this->uri_string == '') {
				$this->_set_request(array($this->default_controller, $this->default_method));
			} else {
				$this->_explode_segments();
				$this->_set_request($this->segments);
			}

			$this->args = array_slice($this->segments, 2);
			$this->_check_args();

		}
		return;
	}

	// --------------------------------------------------------------------
	/**
	 * Get the URI String
	 */
	function _fetch_uri_string()
	{
		$this->uri_string = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
		$this->uri_string = trim($this->uri_string, '/');

	/* REQUEST_URI
		$this->uri_string = $this->_parse_request_uri();
	//	return;*/

		if ($this->module_config['url_suffix']) {
			$this->uri_string = $this->_remove_url_suffix();
		}
	}

	// --------------------------------------------------------------------
	function _set_request($segments = array())
	{
		$this->_add_CM_in_segment($segments);

		if (! file_exists(realpath(dirname(__FILE__)) . '/../main/'. $segments[0] .'.php')) {
			redirect_header(XOOPS_URL.'/', 2, 'No Controller File');//TODO
		}

		if (count($segments) == 0) {
			return;
		}

		$this->set_class($segments[0]);

		if (! isset($segments[1])) {
			$segments[1] = $this->default_method;
		}
		$this->set_method($segments[1]);

		$this->segments = $segments;
	}

	function _add_CM_in_segment(&$segments)
	{
	}

	function _add_CM_in_query()
	{
	}

	// --------------------------------------------------------------------
	function set_class($class)
	{
		$this->class = $class;
	}

	function fetch_class()
	{
		return $this->class;
	}

	function set_method($method)
	{
		$this->method = $method;
	}

	function fetch_method()
	{
		return $this->method;
	}

	function fetch_args()
	{
		return $this->args;
	}

	// --------------------------------------------------------------------
	/**
	 * Parse the REQUEST_URI (UNUSED / someday USE?)
	 */
	function _parse_request_uri()
	{
		if (! isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '') {
			return '';
		}

		$request_uri = preg_replace("|/(.*)|", "\\1", str_replace("\\", "/", $_SERVER['REQUEST_URI']));
		if ($request_uri == '') {
			return '';
		}

		$root_path = XOOPS_ROOT_PATH;
		if ($this->module_config['url_approach'] < 3) {
			$root_path .= '/modules/';
		}
		$root_path .= $this->mydirname;

		if (strpos($request_uri, '?') !== FALSE)
		{
			$root_path .= '?';
		}

		if ($this->module_config['url_suffix'] != "") {
			$request_uri = preg_replace("|".preg_quote($this->module_config['url_suffix'])."$|", "", $request_uri);
		}

		$parsed_uri = explode("/", $request_uri);

		$i = 0;
		foreach (explode("/", $root_path) as $segment) {
			if (isset($parsed_uri[$i]) && $segment == $parsed_uri[$i]) {
				$i++;
			}
		}

		$parsed_uri = implode("/", array_slice($parsed_uri, $i));

		if ($parsed_uri != '') {
			$parsed_uri = '/'.$parsed_uri;
		}

		return $parsed_uri;
	}


	// --------------------------------------------------------------------
	function _remove_url_suffix()
	{
		$temp_url_string = $this->uri_string;

		if ($this->module_config['url_suffix'] != "") {
			$temp_url_string = preg_replace("|".preg_quote($this->module_config['url_suffix'])."$|", "", $temp_url_string);
		}

		return $temp_url_string;
	}

	// --------------------------------------------------------------------
	function _explode_segments()
	{
		foreach(explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val)
		{
			$val = trim($this->_filter_uri($val));

			if ($val != '') {
				$this->segments[] = $val;
			}
		}
	}


	// --------------------------------------------------------------------
	function _filter_uri($str)
	{
		if ($str != '' && $this->permitted_uri_chars != '') {
			if (!preg_match("/^[" . $this->permitted_uri_chars . "]+$/i", $str)) {
				die('The URI has disallowed characters.');	//TODO
			}
		}

		return $str;
	}


}
