<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

include_once LAB_PATH_KERNEL.'/classes/Url.php';

class Url_Flex implements Url
{
	static function parse()
	{
		$parsed=self::parseToArray($_SERVER['REQUEST_URI']);
		if (!$parsed) {
			header('Location:/');
			exit;
		}
		
		if ($_REQUEST['redirect']) {
			if (!User::checkToken($_REQUEST['token'], false)) {
				unset($_GET['redirect'], $_POST['redirect'], $_REQUEST['redirect']);
			}
		}
		
		if (count($parsed)) {
			foreach ($parsed as $key=>$var) {
				$_REQUEST[$key]=$_GET[$key]=$var;
			}
		}
		$_SERVER['PHP_SELF']=$_REQUEST['url'];
	}
	
	static function parseToArray($uri)
	{
		$init_url=@parse_url($uri, PHP_URL_PATH);
		if (!$init_url) return false;
		$parsed=array();

		if (preg_match('/^(.*)\.(xml|js|json)$/', $init_url, $result)) {
			$parsed['data_type']=$result[2];
			$init_url=$result[1];
		}
			//если расширение указано и совпадает с дефолтным - откусываем его
 		elseif ($init_url!='/' && substr($init_url, -strlen(LabConfig::$cfg['ext']))==LabConfig::$cfg['ext'])
			$init_url=substr($init_url, 0, -strlen(LabConfig::$cfg['ext']));
		
		if ($init_url!='/') $init_url=rtrim($init_url, '/');
		
		if (preg_match('/^([^.\-]+)(.*)/', $init_url, $result)) {
			$parsed['url']=$result[1];
			$init_url=$result[2];
		}
		if (preg_match('/^-([^.]+)(.*)/', $init_url, $result)) {
			$parsed['action']=$result[1];
			$init_url=$result[2];
		}
		if ($parsed['url']=='/index') {
			$parsed['url']='/';
		}
		
		$init_url=preg_replace('/^\./', '', $init_url);
		$vars=explode('/', $init_url);
		if(count($vars))
		foreach ($vars as $key=>$var) {
			if ($var!='') {
				$parsed['var'.($key+1)]=rawurldecode($var);
			}
		}
		return $parsed;
	}
	
	static function create($params, $action, $type, $href, $redirect, $token)
	{
		$url='';
		if (!is_array($params) && $params) $params=array($params);
		if (!$href) $href=$_SERVER['PHP_SELF'];
		if ($action) $url="-".$action;
		if($redirect) {
			$params['redirect']=$redirect;
			if (!$token) $token=User::i()->token;
		}
		if($token) $params['token']=$token;
		
		if ($params && $count=count($params)) {
			$vars=array();
			if ($count>1) ksort($params);
			foreach ($params as $key=>$param) {
				if (is_int($key)) {
					$vars[]=urlencode($param);
					unset($params[$key]);
				}
			}
			if (count($vars)) $url.=".".implode('/', $vars);
		}
		
		if ($href!="/" || $action) {
			if (!$type) $url.=LabConfig::$cfg['ext'];
			else $url.=".".$type;
		}
		
		if ($params && count($params)) {
			$url.='?'.http_build_query($params);
		}
		return $href.$url;
	}
	
	static function filter($url)
	{
		return convert_url($url);
	}
}
