<?php
/*
=================================
H E L L Y
---------------------------------
@author : Fesor
@email : fesors@gmail.com
@homepage: http://helly.fesor.ru
@version : 0.8 RC1
@date : 07.08.2009
=================================
*/
class router
{
private static $uri, $params, $route, $app;
function __construct()
{
/* Match URI string */
//on htaccess isn't in use
if( strpos( $_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'] ) !== false )
self::$uri = substr( $_SERVER['REQUEST_URI'], strlen( $_SERVER['SCRIPT_NAME'] )+1 );
else
self::$uri = substr( $_SERVER['REQUEST_URI'], strlen(substr(ROOT, strlen($_SERVER['DOCUMENT_ROOT']))) );
$uriSegments = explode('/', self::$uri);
self::$uri = array();
foreach($uriSegments as $segment)
if($segment !== '')
self::$uri[] = $segment;
//Check for Page param
if(self::$uri[count(self::$uri)-2] == 'page' AND is_numeric(self::$uri[count(self::$uri)-1]))
{
$_GET['page'] = self::$uri[count(self::$uri)-1];
unset(self::$uri[count(self::$uri)-1]);
unset(self::$uri[count(self::$uri)-2]);
}
//Match application
$apps = system::getConfig('apps');
if(isset($apps[self::$uri[0]]))
{
self::$app = $apps[self::$uri[0]];
unset(self::$uri[0]);
}
else
self::$app = system::getConfig('defaultApp');
self::$uri = implode('/', self::$uri).'/';
if(self::$uri == '/')
self::$route = (system::getConfig('defaultController', self::$app) == null ? self::$app:system::getConfig('defaultController', self::$app)).'/index';
elseif(preg_match("/^([A-Za-z0-9\-\_]+)\.html\/$/Uis",self::$uri,$matches))
{
self::$route = 'page/show';
$_GET['name'] = $matches[1];
self::$app = 'pages';
}
else{
$rules = system::getConfig('routing', self::$app);
if(!is_array($rules))
self::http404();
foreach($rules['rules'] as $template=>$route)
{
if( $find = preg_match(self::makePattern($template), self::$uri, $matches) )
{
self::$route = $route;
foreach(self::$params as $key=>$value)
$_GET[$key] = $matches[$key];
break;
}
}
}
}
public function getAppName()
{
return self::$app;
}
public function getRoute()
{
return self::$route;
}
public function getURIstring()
{
return self::$uri;
}
private function makePattern($pattern)
{
if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
self::$params=array_combine($matches[1],$matches[2]);
else
self::$params=array();
$p=rtrim($pattern,'*');
$append=$p!==$pattern;
$p=trim($p,'/');
$template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
if(($pos=strpos($p,'<'))!==false)
$signature=substr($p,0,$pos);
else
$signature=$p;
$tr['/']='\\/';
foreach(self::$params as $key=>$value)
$tr["<$key>"]="(?P<$key>".($value!==''?$value:'[^\/]+').')';
$pattern='/^'.strtr($template,$tr).'\/';
if($append)
$pattern.='/u';
else
$pattern.='$/u';
return $pattern."is";
}
public static function http404()
{
header("HTTP/1.0 404 Not Found");
die("<h1>404 Error</h1>\n<p>".system::message('Page not found!')."</p>");
}
}