<?php

/*
	Stempora web framework
	copyright (c) 2002-2013 Stempora
		web:  www.stempora.com
		mail: support@stempora.com

*/

// IIS
// this is suposed to be a bug fix for those crappy IIS servers which doesnt know what
// REQUEST_URI is, FUCK MICROSOFT

if (!isset($_SERVER["REQUEST_URI"])) {
	$_SERVER["REQUEST_URI"] = 
			(strtoupper($_SERVER["HTTPS"]) == "on" ? "https://" :  "http://") . 
			$_SERVER["SERVER_NAME"] . 
			($_SERVER["SERVER_PORT"] != 80 ? ':' . $_SERVER["SERVER_PORT"] : '') .
			$_SERVER["SCRIPT_NAME"] .
			( $_SERVER["QUERY_STRING"] ? '?' . $_SERVER["QUERY_STRING"] : '' );
}

if (!defined("_3RDPATH")) {
	define("_3RDPATH" , "3rdparty/");
}

// do a fast check for the modules path
if (!defined("_MODPATH")) {
	define("_MODPATH" , "modules/");
}

// do a fast check for the modules path
if (!defined("_TPLPATH")) {
	define("_TPLPATH" , "templates/");
}

if (!defined("_LANGPATH")) {
	define("_LANGPATH" , "lang/");
}

if (!defined("_LOCALPATH")) {
	define("_LOCALPATH" , "local/");
}

if (!defined("_LIBPATH")) {
	define("_LIBPATH" , "lib/");
}

//by commenting this lines you cna enable / disable the xml cacheing
if (!defined("_XMLCACHE")) {
//	define("_XMLCACHE" , "./xml/");
}

//work with the cache its must faster then loading each time the xmls

if (!defined("_TPLCACHE")) {
	define("_TPLCACHE" , "./tmp/tplcache/");
}

//by commenting this lines you cna enable / disable the object cacheing
//if (!defined("_OBJCACHE")) {
//	define("_OBJCACHE" , "./tmp/objcache/");
//}


//devel stuff only



//$_SITE_IDENTITY_CODE = "<font style='font-size:0px'>L1SMPBOD</font>";





//error_reporting(0);

$coreLibs = array(
		"common.php",
		"common.new.php",
		"xml.php",
		"library.php",
		"module.php",
		"debug.php",
		"plugins.php",
		"html.php",
		"config.php",
		"error.php",
		"database.php",

		"template.php",
		"vars.php",
		"forms.sqladmin.php",
		"forms.php",
		"image.php",
		"mobiledetect.php",  
		"sessions.php",  
//		"messages.php"
	);



if (is_array($coreLibs)) {
	foreach ($coreLibs as $key => $library) {
		if (file_exists(_LIBPATH . $library))
			require_once _LIBPATH . $library;
		else
			die("<b>Error:<.b> Missing Core Library: $library");
	}	
}

//session_start();
SessionManager::sessionStart("STB");


//autodetect the rest of the libraries and load them

$libs = dir(_LIBPATH); 
while (false !== ($entry = $libs->read())) { 

	//check if the extension of the file is .php
	if (CFile::Extension($entry) == "php") {
		//check not to be in the corelibs
		if (!in_array($entry , $coreLibs) && ($entry != "site.php")) {
			require_once _LIBPATH . $entry;
		}			
	}
} 
$libs->close(); 


class CBase {
	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $html;
	
}
class CSite {

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $admin;
	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $html;

	/**
	* description
	*
	* @var type
	*
	* @access type
	*/
	var $rewriteRules;
	
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function CSite($xml , $admin = false , $preload_modules = true) {
		global $_CONF , $base , $_VARS ,$_MODULES;

			
		$this->admin = $admin;
		$this->preload = $preload_modules;

		$this->modules = &$_MODULES;

		//loading the config
		$tmp_config = new CConfig($xml);

		$_CONF = $tmp_config->vars["config"];

		//fix the paths
		if (($this->admin) && is_array($_CONF["paths"])){
			$_CONF["upload"] = $_CONF["paths"]["admin"]["upload"];
			$_CONF["path"] = $_CONF["paths"]["admin"]["path"];
			$_CONF["url"] = $_CONF["paths"]["admin"]["url"];
		} else {
			$_CONF["upload"] = $_CONF["paths"]["site"]["upload"];
			$_CONF["path"] = $_CONF["paths"]["site"]["path"];
			$_CONF["url"] = $_CONF["paths"]["site"]["url"];
		}


//		echo "<table><tr><td><pre style=\"background-color:white\">";
//		print_r($_CONF);

		$GLOBALS["_SESS"] = &$_SESSION[$_CONF["site"]];
			

		//loading the templates

		if ($this->admin) {
			//okay we rock
			if ($_CONF["admin"]["template"] != "") {
								
				$tpl = is_array($_CONF["admin"]["template"]) ? $_CONF["admin"]["template"]["tpl"] : $_CONF["admin"]["template"];
				$current_template = $GLOBALS["_SESS"]["current"]["template"] ? $GLOBALS["_SESS"]["current"]["template"] : $tpl;

				//check to see if the template exists
				if (!file_exists(_TPLPATH . $current_template . "template.xml"))
					$current_template = $_CONF["admin"]["template"];
				
				//okay, read the template now
				$template = new CConfig(_TPLPATH . "template.xml");
				$conf = $template->vars["template"];
				//now lets load the templates


				if (is_array($conf["templates"])) {
					foreach ($conf["templates"] as $key =>$tpl) {						
						if ($key != "path") {
							$this->templates[$key] = new CTemplate(_TPLPATH . $conf["templates"]["path"] . $tpl);
						}
					}					
				}

				
			} 

			if (is_array($_CONF["templates"]["admin"])) {
				foreach ($_CONF["templates"]["admin"] as $key => $val) {
					if ($key != "path")
						$this->templates[$key] = new CTemplate($_CONF["templates"]["admin"]["path"] .$val);
				}			
			}		
		} else {

			//allow both methods of having the data in the <site> or directly in the root
			if (is_array($_CONF["templates"]["site"]))
				$_CONF["templates"] = $_CONF["templates"]["site"];

			if (is_array($_CONF["templates"])) {
				foreach ($_CONF["templates"] as $key => $val) {
					if (($key != "path" ) && ($key != "admin"))
						$this->templates[$key] = new CTemplate($_CONF["templates"]["path"] . $_CONF["templates"][$key]);
				}				
			}
		}


		$base = new CBase();
		$base->html = new CHtml();
		$this->html = &$base->html;
		$base->htmlElements = new CHtmlElements();
		$base->XMLFormLanguage  = new CXMLFormLanguage();

		$base->device = new Mobile_Detect();


		if (file_exists(_LIBPATH . "../mysql.php")) { 
				require(_LIBPATH . "../mysql.php"); 
		}  else {
			if (file_exists(_LIBPATH . "../../upload/conf/database.php")) { 
				require(_LIBPATH . "../../upload/conf/database.php"); 
			} 		
		}

		//make a connection to db
		if (is_array($_CONF["database"])) {

			$this->db = new CDatabase($_CONF["database"]);

			//vars only if needed
			if ($_CONF["tables"]["vars"]) {
				$this->vars = new CVars($this->db , $_CONF["tables"]["vars"]);
				$base->vars = &$this->vars;
				$_VARS = &$this->vars->data;
			}

			//some preinit related to datezone 

			$this->tables = &$_CONF["tables"];
		}				
		
	}

	function TableFiller($item) {
		if (file_exists("pb_tf.php")) {
			include("pb_tf.php");
		}
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function Run() {


		global $_TSM , $_SITE_IDENTITY_CODE, $_CONF , $_USER , $_VARS , $_PAGE , $base , $_SESS , $_MODULES;
		$_USER = $_SESS["minibase"]["raw"];

		//read all modules dinamicaly ( from the modules folder )
		$_CONF["modules"] = CDir::GetFolders(_MODPATH );
		
		//read all the preexecute files
		if (is_dir(_LOCALPATH)) {
			$locals = dir(_LOCALPATH); 
			while (false !== ($entry = $locals->read())) { 
			   if (strstr($entry , "pre.")) {
				   include_once(_LOCALPATH . $entry);
			   }			   
			} 
			$locals->close(); 
		}

		//do a module detection now
		if ($this->admin) {
			
			//okay, first be a bitch and do the autentification thingy
			if (!$_SESS["minibase"]["user"]) {

				if ($_GET["mod"] != "auth") {
					$_TSM["redirect"] = $_SERVER["REQUEST_URI"];
				}

				//force to the auth module
				$_GET["mod"] = "auth";
				
				$_CONF["modules_back"] = $_CONF["modules"];
				unset($_CONF["modules"]);
				$_CONF["modules"]["auth"] = "auth";

				//no action = login screen

				//$_GET["action"] = "";
			} else {
				//in case there is specified and index.php?redirect=/.///
				if ($_GET["redirect"]) {
					die("error");
					header("Location: " . urldecode($_GET["redirect"]));
					exit;
				}				
			}
		}


		if (is_array($_CONF["modules"])) {

			//okay initialize the new module now;
			foreach ($_CONF["modules"] as $_KMOD => $_MOD) {				

					$file = _MODPATH . $_MOD . "/" . ($this->admin ? "admin.php" : "site.php");

					//trying to add the cacheing to modules too 

					$found = false;
					$cache = false;

					//detect if the file exists
					if (file_exists($file) && !$found) {						
						
						require_once $file;
						eval("\$_MODULES[\"". $_MOD. "\"] = new c{$_MOD}();");				
						//send the used params

						$_MODULES[$_MOD]->name				= $_MOD;
						$_MODULES[$_MOD]->admin				= $this->admin;

						$_MODULES[$_MOD]->templates			= &$this->templates;

						//keep compatibilitt withg all reflex programing
						$_MODULES[$_MOD]->tables			= &$this->tables;
						$_MODULES[$_MOD]->private->tables	= &$this->tables;
						$_MODULES[$_MOD]->vars				= &$this->vars;
						$_MODULES[$_MOD]->private->vars		= &$this->vars;
						$_MODULES[$_MOD]->db				= &$this->db;
						$_MODULES[$_MOD]->plugins			= &$_MODULES;

						//compatibility with existing modules
						$_MODULES[$_MOD]->module->plugins	= &$_MODULES;

						$_MODULES[$_MOD]->path				= _MODPATH . $_MOD . "/";
						$_MODULES[$_MOD]->tpl_path			= _MODPATH . $_MOD . "/templates/";
						$_MODULES[$_MOD]->forms_path		= _MODPATH . $_MOD . "/forms/";
						$_MODULES[$_MOD]->ext_path			= _MODPATH . $_MOD . "/extensions/";

						$_MODULES[$_MOD]->__load();

					}

			}

//			foreach ($_MODULES as $_KMOD => $_MOD) {				
				//$_MODULES[$_KMOD]->__preinit();
//			}



			//added another set of extra fields to be executed after the modules initialisation but before executing the actual module
			if (is_dir(_LOCALPATH)) {
				$locals = dir(_LOCALPATH); 
				while (false !== ($entry = $locals->read())) { 
				   if (strstr($entry , "run.")) {
					   include_once(_LOCALPATH . $entry);
				   }			   
				} 
				$locals->close(); 
			}


			foreach ($_MODULES as $_MOD => $_MODULE) {
			
				$_CONF["forms"]["adminpath"] = $_MODULE->forms_path . "/";


				if ($_GET["mod"] == $_MOD) {
					//if its the current module then execute that module and put the return in PB_EVENTS
					$_TSM["PB_EVENTS"] = $_MODULES[$_MOD]->DoEvents();
				} else {
					//just execute the module and it will do the restu of the actions
					$_MODULES[$_MOD]->DoEvents();
				}
						

				if ($this->admin) {
			
					//execute the admin generation function
					$_MODULES[$_MOD]->__adminMenu();

					if (is_array($_MODULES[$_MOD]->private->menu)) {
						foreach ($_MODULES[$_MOD]->private->menu as $key => $val) {
							if ($val["pos"]) {
								$menu[$val["pos"]][] = $val;
							} else {
								$menu["left"][] = $val;
							}							
						}						
					}
				
					//debug($_MODULES[$_MOD]->private->menu);
				}
				
			}
			

		}


		if ($this->admin) {

			if (is_array($menu)) {
				$menu_obj = new CAdminMenu();

			

				foreach ($menu as $key => $val) {

					if (is_object($this->templates["menus.{$key}"])) {
						$menu_obj->template = &$this->templates["menus.{$key}"];
						$menu_obj->menu = $val;

						if ($key == "left") {
							$menu_obj->sort = false;
						} else {
							$menu_obj->sort = true;
						}						

						$_TSM["MENU:" . strtoupper($key)] = $menu_obj->Render();
					}						

				}
				
			}			
		}

		if (!$_TSM["PB_EVENTS"]) {
			$_TSM["PB_EVENTS"] = "";
		}
			

		//add the local files, the after executions ones
		//read all the files
		if (is_dir(_LOCALPATH)) {
			$locals = dir(_LOCALPATH); 
			while (false !== ($entry = $locals->read())) { 
			   if ((substr($entry , 0 , 6) == "after.") && (strstr($entry , ".php"))) {
				   include_once(_LOCALPATH . $entry);
			   }			   
			} 
			$locals->close(); 
		}


		if (HTML_MINIFY) {
			ob_start("sanitize_output");
		}
		

		if (isset($_PAGE)) {

			if (stristr($_PAGE , "/") ) {
				$path = $_PAGE . "/layout.xml";
			} else {
				$path = $_CONF["path"] . "layouts/$_PAGE/layout.xml";
			}

			//debug(($_CONF["template_path"] ?  $_CONF["template_path"] : $_CONF["path"]). "templates/$_PAGE/layout.xml");

			//$this->layout = new CLayout(($_CONF["template_path"] ?  $_CONF["template_path"] : $_CONF["path"]). "templates/$_PAGE/layout.xml");		
			$this->layout = new CLayout($path);		
			$this->layout->Build();


			//handle global variables for languages
			global $_LANG_DATA;

			if (is_array($_LANG_DATA)) {
				$this->layout->Replace($_LANG_DATA);
			}
			

			if (is_dir(_LOCALPATH)) {
				$locals = dir(_LOCALPATH); 
				while (false !== ($entry = $locals->read())) { 

				   if ((substr($entry , 0 , 7) == "render.") && (strstr($entry , ".php"))) {
					   include_once(_LOCALPATH . $entry);
				   }			   
				} 
				$locals->close(); 
			}

			$this->layout->Show();

		} else {
						
			if (is_object($this->templates["layout"])) {
				echo $this->templates["layout"]->Replace($_TSM);
			}		
		}
	}
}


function sanitize_output($buffer) {

/*

    $search = array(
        '/\>[^\S ]+/s',  // strip whitespaces after tags, except space
        '/[^\S ]+\</s',  // strip whitespaces before tags, except space
        '/(\s)+/s'       // shorten multiple whitespace sequences
    );

    $replace = array(
        '>',
        '<',
        '\\1'
    );

    $buffer = preg_replace($search, $replace, $buffer);

*/

	require_once _3RDPARTY . "minify/htm.php";

    return Minify_HTML::minify($buffer);
}



?>