Location: PHPKode > projects > Itshomi PHP Framework > itshomi/Navigator.php
<?
/*************************************************************
*                     File: Navigator.php                    *
*                 Copyright ALM Software Technologies             *
*                         www.softwaretechnologies.co.za                   *
*                  Created by: Fernando Martinez             *
*                        30/01/04                            *
**************************************************************/
if(!is_dir($itshomidir))
    die('Please configure your Itshomi directory');
include_once($itshomidir.'/ImiComponent.php');
include_once($itshomidir.'/components/dbtable/Dbtable.php');
include_once($itshomidir.'/utils/Util.php');

set_include_path(get_include_path() . PATH_SEPARATOR . $itshomidir.'/lib/');
if($path!=$itshomidir)
	set_include_path(get_include_path() . PATH_SEPARATOR . $path.'/lib/');
/**
 *  class Navigator
 *  purpose: application navigation controller.
 */  
class Navigator extends ImiComponent
{
    private $path,$config,$configurator = null,$imipath;
	public $entry = 'web';
	private $viewData = array('MAIN_MENU'=>'','LOGO'=>'','BANNER'=>'','FOOTER'=>'','CONTENT_HEAD'=>'','TITLE'=>'','FEEDBACK'=>'','LOGIN_FRM'=>'','TOP_MENU'=>''),$views = array();
  
    function __construct(){ 
        global $path,$config,$entrylevel,$itshomidir;
        $this->path = $path;
		$this->imipath = $itshomidir;
        $this->config = &$config;
		$this->entry = $entrylevel;
		$GLOBALS['dbtype']=$config['dbtype'];
    }
    
    function &getInstance($cname){
        if(($comp=$this->getComponent($cname))==null)
            return $this->instantiate($cname);
		return $comp;	
    }
    
    function &instantiate($cname){ 
        global $compsdir,$itshomidir;
        $fd = strtolower($cname);$cname = ucfirst($fd);
        $compPath = $this->path."/".$compsdir."/".$fd."/";
        $task = '';
        if(isset($_REQUEST[$this->config['def_webev_label']]))
                $task = $_REQUEST[$this->config['def_webev_label']];
        if(file_exists($compPath.$cname.".php")){
            include_once($compPath.$cname.".php");
            $comp = &$this->newObj($cname);
            if(isset($comp)){
				$comp->setName($cname);
            	$comp->setPath($compPath);
            	$comp->setTask($task);
                $this->addComponent($cname,$comp);
                return $comp;
            }
        }
	$compPath = $this->imipath."/components/".$fd."/";
        if(file_exists($compPath.$cname.".php")){
            include_once($compPath.$cname.".php");
            $comp = &$this->newObj($cname);
            if(isset($comp)){
				$comp->setName($cname);
            	$comp->setPath($compPath);
            	$comp->setTask($task);
                $this->addComponent($cname,$comp);
                return $comp;
            }
        }
        throw new Exception('Failed to instantiate '.$cname.': component not found');
    }
    
    /**
     * loads a given class
     * @param $fullFolderPath absolute path to class folder
     * @param $classname class name
     * @see /ImiComponent#getClass($classname)
     */
	function &getClass($fullFolderPath,$classname){
		if(file_exists($fullFolderPath.$classname.".php")){
			include_once($fullFolderPath.$classname.".php");
			return $this->newObj(basename($classname));
		}else
			throw new Exception('Class '.$classname.' not found in Navigator->getClass for given path:'.$fullFolderPath);
	}
	
	/**
	 * loads a given utility class
	 * @param $classname class name
	 * @see /ImiComponent#getUtil($classname)
	 */
	function &getUtil($classname){
		if(file_exists($this->imipath."/utils/".$classname.".php")){
			include_once($this->imipath."/utils/".$classname.".php");
			return $this->newObj(basename($classname));
		}else
			throw new Exception('Class '.$classname.' not found in /utils');
	}
	/**
	 * 
	 * @return application's path
	 */
	function getPath(){
		return $this->path;
	}
	
	/**
	* executes a component passing a given event and layout
	*/
	function playComponent($comp,$evName,$layout = null){
		$component = &$this->getInstance($comp); 
		if($this->config['appmode']=='debug')
			addlog("sending ev:".$evName." to comp:".$comp." layout is ".$layout,'sys','debug','imi');
		if(isset($component)){
			$component->setTask($evName);
			if($layout!=null)		
				$component->setLayout($layout);
			$component->play();
		}else
			$this->getInstance('def_error')->play('Unknown request');
	}
	
	/**
	* load application configuration
	*/
	function loadConfig(){
		if($this->config['appinstalled']==false)
			return false;
		$this->configurator = $this->getInstance('configurator');
		$this->configuration = &$this->configurator->onStartup();
		return (count($this->configuration)>1);
	}
	
	/**
	* return a configuration parameter
	*/
	function getCfg($varname){
		return $this->configuration[$varname];
	}
	
	/**
	* set a configuration parameter
	*/
	function setCfg($varname,$value){
		$this->configuration[$varname]=$value;
	}
	
    function dispatch(){
		if(!$this->loadConfig())
		{
			if(!isset($this->configurator)){
				if(file_exists('install/en_Installer.php'))
					header('Location: install/en_Installer.php');
				else
					die("Your application does not appear to be installed but the installation files could not be found. Please copy again the application original files and point your browser to the root location");
			}else
				header('Location: config/en_SysConfig.php');	
		}
		try{	
			$this->configuration = array_merge_recursive($this->configuration,$this->config);
			$this->dispatchEvent('ON_LOAD');
			if(isset($_REQUEST[$this->config['def_webev_label']])){
				$this->dispatchEvent($_REQUEST[$this->config['def_webev_label']]);
			}else	
				$this->dispatchEvent($this->configuration['default_event']);  
		}catch(Exception $e){
			addlog($e->getMessage());
			if($e->getMessage()=='Access denied')
				$this->getInstance('def_error')->play('Access to this page is restricted. You must login with the appropriate user rights');
			else	
				$this->getInstance('def_error')->play('An error occurred while processing your request');
		}	         
    }
    
	function activeComponent($c){
		foreach($this->config['components'][$this->entry] as $comp){
			if($c===$comp)
				return true;
		}
		return false;
	}
	
	/**
	*  add component as listener 
	*  @param $evName event name
	*  @param $listener component name
	*  @param $evType (optional)
	*  @param $viewid (optional)
	*/
	function addListener($evName,$listener,$evType=2,$viewid=0){
		$sz = count($this->config['events'][$evName]['listeners']);
		$this->config['events'][$evName]['listeners'][$sz]=$listener;
		$dbtable = $this->getInstance('dbtable');
		$dbtable->useTable('workflow');
		$sql = "insert into workflow(component,task,viewid,evtype) values('".$listener."','".$evName."',".$viewid.",".$evType.")";
		if($dbtable->execStmt($sql)){
			addlog("Component ".$listener." is now listening for event ".$evName);
		}else
			addlog("Failed to add ".$listener." as listener for event ".$evName);
	}
	
	function removeListener($evName,$listener){
	// TODO:
	}
	
	/**
	*  @param $evName event name
	*/
	function dispatchEvent($evName){ 
		if($this->config['appmode']=='debug')
			addlog('dispatching event:'.$evName,'sys','debug','imi');
		if(isset($this->configuration['events'][$evName]['listeners'])){
			foreach($this->configuration['events'][$evName]['listeners'] as $comp){
				$this->playComponent($comp,$evName);
			}
		}
	}
	
    function render(){
		try{
			global $entrylevel;
			if(isset($_REQUEST['qt'])){ 
				if($this->config['appmode']=='debug')
					addlog("qt defined and ev=".$_REQUEST[$this->config['def_webev_label']],'sys','debug','imi');
				if(isset($_REQUEST["feedback"]) && strlen($_REQUEST["feedback"])>0){
					$output = "<h3>".$_REQUEST['feedback']."</h3>";
				}else
					$output="";
				$output.=$this->renderViews();
				eval('?>' .$output);
				$output = ob_get_clean();
				die($output);	
			}
			if($entrylevel == 'web'){
				$templatePath = $this->configuration['web_template'];
				if($this->config['appmode']=='debug')
					addlog("request from web entry level",'sys','debug','imi');
			}else
			if($entrylevel == 'admin'){
				$templatePath = $this->configuration['adm_template'];
				if($this->config['appmode']=='debug')
					addlog("request from adm entry level",'sys','debug','imi');
			}else
			if(($templatePath = $this->configuration[$entrylevel])!=null){
				if($this->config['appmode']=='debug')
					addlog("request from ".$entrylevel,'sys','debug','imi');
			}else{
				addlog('Unknown entry level in Navigator->render');
				die("");
			}		
			$template = file_get_contents($templatePath);
			
			$this->addViewData('FEEDBACK','<?
		if(isset($_REQUEST["feedback"]) && strlen($_REQUEST["feedback"])>0){ 
			echo("<h3>".$_REQUEST["feedback"]."</h3>");
		}?>');
			foreach($this->config['renderer']['events'] as $renderEvent){
				$this->dispatchEvent($renderEvent);
			}
			$keys = array_keys($this->viewData);
			foreach($keys as $key){ 
				$template = str_replace('{$'.$key."}",$this->viewData[$key],$template);
			}
			$template = str_replace('{$NEWS_FLASH}','&nbsp;',$template);
			$template = str_replace('{$AHEADER}',$this->getJsLib(),$template);
				$template = str_replace('{$CONTENT_TEXT}',$this->renderViews(),$template);
				$template = str_replace('{$SITE_LOGO}',$this->config['sitelogo'],$template);
			$template = str_replace('{$DEF_EV}',$this->config['def_webev_label'],$template);
			
			include_once($this->path."/config/appvars.php");
			foreach($appvar as $key => $val){ 
				$template = str_replace('{$'.$key."}",$val,$template);
			}
			for($i=1;$i<10;$i++){
				$template = str_replace('<a href="{$APPMNU1_'.$i.'}" title="{$APPMNU1_'.$i.'_TITLE}">{$APPMNU1_'.$i.'_LBL}</a>','',$template);
                $template = str_replace('<a href="{$APPMNU2_'.$i.'}" title="{$APPMNU2_'.$i.'_TITLE}" alt="{$APPMNU2_'.$i.'_TITLE}">{$APPMNU2_'.$i.'_LBL}</a>','',$template);
			}
			if($entrylevel == 'admin'){
				$template = str_replace('index.php','admin.php',$template);
			}
			if($this->config['appmode']=='debug')
				file_put_contents('tmp\output.php',$template);
			eval('?>' .$template);
			$template = ob_get_clean();
			if($this->config['appmode']=='debug')
				file_put_contents('tmp\output2.php',$template);
	
			$template = str_replace('{$DEF_EV}',$this->config['def_webev_label'],$template);
			$template = str_replace('{$EVENT_LBL}',$this->config['def_webev_label'],$template);
			echo($template);
		}catch(Exception $e){
			addlog($e->getMessage());
			if($e->getMessage()=='Access denied')
				$this->getInstance('def_error')->play('Access to this page is restricted. You must login with the appropriate user rights');
			else	
				$this->getInstance('def_error')->play('An error occurred while processing your request');
		}
    }
    
	function getJsLib(){
		$jslib = '&nbsp;';
		switch($this->config['jslib']){
			case 'jquery':
				$jslib = '
				<link type="text/css" href="js/jquery/themes/start/ui.all.css" rel="stylesheet" />
				<script type="text/javascript" src="js/jquery/jquery-1.3.2.js"></script>
	<script type="text/javascript" src="js/jquery/ui/ui.core.js"></script>
	<script type="text/javascript" src="js/jquery/ui/ui.tabs.js"></script>
	
	<script type="text/javascript">
	$(function() {
		$("#tabs").tabs();
		$("a#imiaj").bind("click", function(){ 
			$(\'#content\').load("index.php?{$DEF_EV}="+$(this).text()+"&qt=aj");
			return false;
		});
		writeDate();
	});
	function writeDate(){
		$("#ddate").html("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+new Date().toDateString());
	}
	</script>';
			break;
		}
		return $jslib;
	}
	
    function renderViews(){
    	$nv = count($this->views);
    	$vdata = "";
		if($this->config['appmode']=='debug')
			addlog("Rendering ".$nv." views",'sys','debug','imi');
		for($i=0;$i<$nv;$i++)
		{
			if(strpos($this->views[$i],"CV_")!==false)
			{
				$vdata.= file_get_contents($$this->views[$i]);
			}else{
				$vname = $this->views[$i];
				if(isset($this->config['alang']) && strlen($this->config['alang'])>0){
					if(($p=strrpos($vname,"/"))!==false){
						$prf = substr($vname,0,($p+1));
						$name = substr($vname,($p+1));
						$vname = $prf.$this->config['alang']."_".$name;
					}else
						$vname = $this->config['alang']."_".$vname;
				}
				if($this->config['appmode']=='debug')
					addlog("loading view:".$vname,'sys','debug','imi');
				$vdata.= file_get_contents($vname);
				$_SESSION['lastview']=$this->views[$i];
			}
		}
      		return $vdata;
    }
    
    function addView($view){
        $n = count($this->views);
        $this->views[$n] = $view;
    }
    
    function addViewData($p,$data){ 
		if(isset($this->viewData[$p]))
        	$this->viewData[$p] .= $data;
		else
			$this->viewData[$p] = $data;	
    }
       
	function getConfig(){
		return $this->config;
	}

	/** create instance of given object */
    function &newObj($object)
    {
	    $obj = new $object();
	    return $obj;
    }
}

$navigator = new Navigator();
$navigator->dispatch();
$navigator->render();
?>
Return current item: Itshomi PHP Framework